Skip to content

Guide · Open source

How to use node-jsonwebtoken: sign and verify JWTs in Node.js

Updated · written with AI from the project's own documentation and checked against our catalogue data

node-jsonwebtoken (the jsonwebtoken npm package) is a JavaScript library for Node.js that creates signed JSON Web Tokens and checks them. This guide shows you how to install it, sign a token with a shared secret or a private key, set expiration, and verify a token safely. By the end you will be able to add token-based checks to a Node.js API.

jsonwebtokenauth0/node-jsonwebtoken · ★ 18.2k · MIT

Quick start

  1. 1Install the package. Run npm install jsonwebtoken in your Node.js project folder.
  2. 2Choose a key type. Use a shared secret for HMAC (HS256, the default) or a PEM private key for RS256 or ECDSA.
  3. 3Sign a token. Call jwt.sign with an object payload, your key, and options such as expiresIn.
  4. 4Set expiration. Use expiresIn with a number of seconds or a string like '1h', or set exp in the payload, but not both.
  5. 5Verify the token. Call jwt.verify with the token and your secret or public key, and pass algorithms to limit what is accepted.
  6. 6Handle errors and read claims. Catch the error that jwt.verify throws when a token is invalid, and read only the payload fields you expect.

What a JSON Web Token does

A JSON Web Token (JWT) is a compact string that carries claims, such as who the user is and when the token expires. It also carries a signature, so the receiver can check that the token was not altered.

The library implements the JSON Web Token standard (RFC 7519). The README notes it was developed against draft-ietf-oauth-json-web-token-08 and uses node-jws underneath.

Install jsonwebtoken in Node.js

The package is installed with npm, so you need Node.js and its package manager available in your project. Run the install command from your project folder.

$ npm install jsonwebtoken

Sign a token with a secret or private key

Call jwt.sign with a payload and a key. The payload should be an object literal, because claims such as exp are only set when the payload is an object. The default algorithm is HS256, which uses a shared secret (HMAC).

For RSA or ECDSA, pass a PEM-encoded private key and set the algorithm option, for example RS256. When signing with RSA, the minimum modulus length is 2048 unless you set allowInsecureKeySizes to true. Smaller keys are rejected with an error.

Signing is synchronous when no callback is given, and asynchronous when you pass a callback.

  • Default: HMAC SHA256 with a secret string
  • RSA: pass the private key and { algorithm: 'RS256' }
  • Async: pass a callback as the last argument
var jwt = require('jsonwebtoken'); var token = jwt.sign({ foo: 'bar' }, 'shhhhh');

Set token expiration with exp or expiresIn

The exp claim is a NumericDate: the number of seconds since 1970-01-01T00:00:00Z UTC. You can set it yourself in the payload, or use the expiresIn option, which accepts seconds or a time-span string.

A numeric expiresIn is read as seconds. A string with no unit is read as milliseconds, so "120" equals "120ms". Always include units in strings, such as "1h" or "7d". You cannot set the same claim in both the payload and the options.

  • Numeric value: 3600 means one hour in seconds
  • String value: '1h' or '7d' (uses vercel/ms formats)
  • Do not set exp in both the payload and expiresIn
jwt.sign({ data: 'foobar' }, 'secret', { expiresIn: '1h' });

Verify a token and read its payload

Call jwt.verify with the token and the secret or public key. If the signature is valid and any optional checks pass, it returns the decoded payload. If not, it throws an error (synchronous) or passes the error to the callback (asynchronous).

Restrict the allowed algorithms with the algorithms option. If you omit it, the library picks defaults based on the key type. Use the audience, issuer, subject and jwtid options to check those claims. Use clockTolerance to allow small clock differences when checking nbf and exp.

Treat the decoded payload as user input when the token comes from an untrusted source. Sanitize it and use only the properties you expect.

  • algorithms: list of allowed algorithms, such as ["HS256"]
  • audience, issuer, subject, jwtid: optional claim checks
  • complete: true returns { payload, header, signature }
  • clockTolerance: seconds of tolerance for nbf and exp
var decoded = jwt.verify(token, 'shhhhh'); console.log(decoded.foo); // 'bar'

Options to adjust signing behaviour

Several signing options control the claims and header. The iat claim is added automatically unless you set noTimestamp. If you include iat in the payload, the library uses that value when it calculates exp from expiresIn.

mutatePayload modifies the payload object you pass in, which can help if you need a reference to the claims after they are applied. Use allowInvalidAsymmetricKeyTypes only for backwards compatibility, since the README says to avoid it.

  • noTimestamp: skip the automatic iat claim
  • header: customize the token header object
  • keyid: set the key identifier
  • mutatePayload: write claims back to your payload object
  • allowInsecureKeySizes: allow RSA keys under 2048 bits (not recommended)
jwt.sign({ foo: 'bar', iat: Math.floor(Date.now() / 1000) - 30 }, 'shhhhh');

What people use it for

  • Issuing a signed token after a user logs in, then checking it on later API requests
  • Signing tokens with an RSA private key so other services can verify them with the public key
  • Limiting tokens to a specific audience or issuer with the audience and issuer options
  • Setting short expiration times on tokens with expiresIn for session-style access

Frequently asked questions

How do I install node-jsonwebtoken?

Run npm install jsonwebtoken in your Node.js project. The package is named jsonwebtoken on npm, and you require it with require('jsonwebtoken') in your code.

Is jsonwebtoken free to use?

The project is released under the MIT licence, according to the listing. Check the licence file in the repository for the full terms before you ship it.

What do I need to run jsonwebtoken?

You need Node.js, because the package is written for Node.js. It is a code library, so you use it inside your own server or script.

Does jsonwebtoken handle login, user storage or key management?

No. The README covers signing and verifying tokens only. You still need to write the login flow, store users, and manage your secrets or keys yourself.

Why does my token fail verification?

Common causes are a wrong secret or key, an expired exp claim, an audience or issuer that does not match your options, or an algorithm not in the algorithms list. The error thrown by jwt.verify tells you which check failed.

How does jsonwebtoken compare to jose or passport-jwt?

jose, passport-jwt and fast-jwt are listed as comparable projects. jsonwebtoken is a general sign-and-verify library; passport-jwt is built for use with the Passport authentication middleware. Compare them on the features you need before choosing.

New agent skills, repos and AI tools — every week

The best new skills and open-source projects, the fastest-growing repos, and one free prompt. Five minutes to read. Unsubscribe anytime.

Our verdict

Use node-jsonwebtoken if you build a Node.js API and want a well-known library to sign and verify JWTs with HMAC or RSA/ECDSA keys, with expiration and claim checks included. Pick something else if you are not using Node.js, or if you need a complete login system, user storage or key management, since this library does none of those.

Install options & downloads