querystring.encode()

Serializes an object into a URL query string; an alias for querystring.stringify().

Signature
querystring.encode()
  • Added in Node.js v0.1.99

Parameters

ParameterTypeDescription
$obj<Object>The object to serialize into a URL query string. Documented under querystring.stringify().
$sepoptional<string>= '&'The substring used to delimit key and value pairs in the query string.
$eqoptional<string>= '='The substring used to delimit keys and values in the query string.
$optionsoptional<Object>Options object; its encodeURIComponent property overrides the encoder used.

Return value

<string>Identical to querystring.stringify(): the object serialized as a query string, with no leading '?'.

Errors

Throws whatever querystring.stringify() throws, notably a URIError (ERR_INVALID_URI) for a lone surrogate in a key or value.

The official documentation lists this member with no parameters, because there is nothing to document: querystring.encode is the very same function object as querystring.stringify. querystring.encode === querystring.stringify evaluates to true. The effective signature is therefore querystring.encode(obj[, sep[, eq[, options]]]), and every behaviour of stringify() applies unchanged — arrays become repeated keys, values that are not strings, finite numbers, bigints or booleans collapse to empty strings, and there is no leading ?.

Why it exists

It is a symmetry alias, added in v0.1.99 alongside querystring.decode (which aliases parse). Some codebases read better as encode/decode; others prefer stringify/parse because it mirrors JSON. Neither is deprecated.

When to reach for it

Reach for the alias only to stay consistent with code that already uses it. In new code prefer stringify() — it is the name the docs describe in full, the name type definitions and search results centre on, and the one a reader will not have to look up. Better still, for anything that is not performance-critical use new URLSearchParams(obj).toString(), which is standardized and works in browsers.

Because the two names share one function object, reassigning one does not affect the other; that asymmetry is worth remembering if you monkey-patch either.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Reading or maintaining older Node code that pairs encode() with decode()
  • Serializing an options object into a query string with encode/decode naming symmetry
  • Confirming during a migration that encode and stringify are not two different behaviours

Frequently asked questions

What is the difference between querystring.encode and querystring.stringify?

There is none — encode is an alias, and querystring.encode === querystring.stringify is true. It was added in v0.1.99 purely to pair with querystring.decode, which aliases querystring.parse.

Is querystring.encode deprecated?

No. The whole node:querystring module is Stability 2 - Stable, and neither alias is marked deprecated; the docs simply recommend URLSearchParams when performance is not critical or browser compatibility matters.

Why does the documentation show querystring.encode() with no arguments?

Because the docs describe it only as an alias and put the full parameter list under querystring.stringify(). It really accepts querystring.encode(obj[, sep[, eq[, options]]]).

More examples

An encode/decode round-trip in legacy code

The pair is lossy in one direction: types are flattened to strings and a single-element array comes back as a bare string. The loadState function shows the coercions any encode/decode round-trip needs — Number(), the === 'true' boolean check, and [].concat() to re-normalise a repeated key.

Example · javascript
const querystring = require('node:querystring');

// Older codebases often store view state as a query string.
function saveState(state) {
  return querystring.encode(state);
}

function loadState(str) {
  const raw = querystring.decode(str);
  return {
    // Everything comes back as a string: coerce explicitly.
    page: Number(raw.page ?? 1),
    sort: String(raw.sort ?? 'name'),
    tags: [].concat(raw.tags ?? []),
    archived: raw.archived === 'true',
  };
}

const stored = saveState({ page: 3, sort: 'date', tags: ['a', 'b'], archived: false });
console.log(stored);
// page=3&sort=date&tags=a&tags=b&archived=false

console.log(loadState(stored));
// { page: 3, sort: 'date', tags: [ 'a', 'b' ], archived: false }

Migrating from encode to URLSearchParams

Two differences show up the moment you swap APIs: an array value becomes a comma-joined string rather than a repeated key, and spaces encode as + instead of %20. Appending each element individually restores the repeated-key shape; the +/%20 difference is harmless to a decoder but will break any byte-for-byte URL comparison.

Example · javascript
const querystring = require('node:querystring');

const params = { q: 'node streams', tag: ['http', 'perf'], page: 2 };

console.log(querystring.encode(params));
// q=node%20streams&tag=http&tag=perf&page=2

// URLSearchParams does not expand arrays: it calls String() on them.
console.log(new URLSearchParams(params).toString());
// q=node+streams&tag=http%2Cperf&page=2

// Expand them explicitly to match.
const sp = new URLSearchParams();
for (const [key, value] of Object.entries(params)) {
  for (const v of [].concat(value)) sp.append(key, v);
}
console.log(sp.toString());
// q=node+streams&tag=http&tag=perf&page=2

Discussion

  • Be the first to comment on this lesson.