Skip to content

Commit

Permalink
refactor(req.query): use native URLSearchParams to parse query params…
Browse files Browse the repository at this point in the history
… string
  • Loading branch information
coldlink committed Dec 19, 2024
1 parent 3b8bbb0 commit 188f0c5
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/server/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,31 @@ const createServer = (): Express => {
// X-Forwarded-For header values (cf. https://expressjs.com/en/guide/behind-proxies.html)
// This is necessary for accurately logging the IP address in rate limiter calls.
server.set('trust proxy', true);

/**
* Use a custom query params parser to solve the issue if duplicate query
* params are present, where qs will parse them into an array.
* e.g. `?foo=bar&foo=baz&hello=world` => `{ foo: ['bar', 'baz'], hello: 'world' }`
* Where what we want is `{ foo: 'baz', hello: 'world' }`, i.e a flat object with
* the last value of the duplicate query param.
*
* Essentially, by default, express will use https://www.npmjs.com/package/qs
* to parse query params, which is more powerful than what we need (called 'extended')
* in the express docs.
* Even the "simple" mode in express uses node's querystring api.
* This will also parse duplicate query params into an array, which is not what we want,
* as shown by the example: https://nodejs.org/api/querystring.html#querystringparsestr-sep-eq-options
*
* However, we can use a custom query parser to use the native URLSearchParams API,
* which will parse duplicate query params into the last value, which is exactly what we want.
* So that `?foo=bar&foo=baz&hello=world` => `{ foo: 'baz', hello: 'world' }`.
* This can be tested in a node repl or browser console by running:
* Object.fromEntries(new URLSearchParams(`foo=bar&foo=baz&hello=world`).entries())
* which returns the expected result.
*/
server.set('query parser', (str: string) =>
Object.fromEntries(new URLSearchParams(str).entries()),
);
applyMiddleware(server);
return server;
};
Expand Down

0 comments on commit 188f0c5

Please sign in to comment.