ThisCalculator

Everyday

JWT Auth in Node.js: What to Know First

Updated · Standard formula, shown below

Approx token size 232 bytes
Token lifetime
60 minutes
You entered
Payload length
100 chars
You entered

Before you build JWT authentication in Node.js, you need to know that JWTs are not a complete authentication solution on their own—they are a token format that must be paired with careful handling of secrets, expiration, and storage to avoid serious security holes. This article explains the core concepts, common pitfalls, and practical decisions you’ll face, so you can implement JWT auth correctly the first time.

What Is JWT and How Does It Work?

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact, URL-safe way to represent claims between two parties. A JWT consists of three parts separated by dots: a header, a payload, and a signature. The header typically specifies the signing algorithm (like HS256 or RS256). The payload contains claims—statements about the user and metadata like expiration (exp) and issued-at (iat). The signature is computed over the header and payload using a secret (for HMAC) or a private key (for RSA/ECDSA).

When a user logs in, your server creates a JWT and sends it to the client. The client stores it and sends it in the Authorization header (usually as Bearer <token>) on subsequent requests. Your server verifies the signature and checks the expiration before trusting the claims. Because the token is self-contained, you don’t need to query a database on every request—that’s the main performance benefit.

Why Use JWT in Node.js?

Node.js is a natural fit for JWT because the ecosystem has mature libraries like jsonwebtoken and jose. JWTs are stateless, which means your API server doesn’t need to store session data. This makes horizontal scaling easier—any server instance can verify a token without sharing session state. JWTs also work well with mobile apps and single-page applications (SPAs) where traditional cookie sessions can be awkward.

However, statelessness is a double-edged sword. You cannot revoke a JWT before it expires (unless you maintain a blacklist, which reintroduces state). That’s why JWTs are best for short-lived access tokens, not long-lived sessions.

How to Choose the Right Signing Algorithm

You have two main choices: HMAC (HS256) and asymmetric algorithms (RS256, ES256). HS256 uses a single secret key for both signing and verification. It’s simple and fast, but the same secret must be shared with every service that verifies tokens. If the secret leaks, attackers can forge tokens. RS256 uses a private key to sign and a public key to verify. This is safer for microservices because only the auth service holds the private key; other services only need the public key. ES256 (ECDSA) offers similar benefits with smaller signatures, but requires careful handling of nonces.

For most Node.js applications, RS256 is recommended if you have multiple services. If it’s a single monolith, HS256 is acceptable, but you must store the secret in an environment variable, never in code.

Common Mistakes and How to Avoid Them

Many JWT implementations fail due to avoidable mistakes:

  • Not verifying the algorithm: Always specify the allowed algorithms in your verification function. An attacker could change the header to “none” or switch from RS256 to HS256 and use the public key as the HMAC secret.
  • Storing tokens in localStorage: localStorage is accessible to any JavaScript on your domain, making it vulnerable to XSS attacks. Prefer httpOnly cookies, which are not readable by JavaScript and are sent automatically by the browser.
  • Ignoring expiration: Set a short expiration (e.g., 15 minutes) for access tokens and use a refresh token for longer-lived sessions. Refresh tokens should be stored securely and rotated on each use.
  • Putting sensitive data in the payload: The payload is base64-encoded, not encrypted. Anyone can decode it. Never put passwords, credit card numbers, or other secrets in a JWT.
  • Not handling clock skew: If your server and client clocks differ, the exp check may fail. Many libraries allow a small leeway (e.g., 30 seconds) to accommodate this.

Access Tokens vs. Refresh Tokens

An access token is short-lived (minutes to hours) and is sent with each API request. A refresh token is long-lived (days to months) and is used only to obtain new access tokens when the old one expires. This two-token approach limits the damage if an access token is stolen, because it expires quickly. Refresh tokens must be stored securely on the server (e.g., in a database with a hash) and should be rotated—each time a refresh token is used, a new one is issued and the old one is invalidated.

In Node.js, you can implement this with a route like POST /refresh that checks the refresh token, verifies it, and issues a new access token. Make sure to revoke refresh tokens on logout and detect token reuse (if an old refresh token is used after rotation, revoke the entire session).

Security Best Practices for JWT in Node.js

Beyond the basics, follow these practices to harden your implementation:

  • Use HTTPS: Always transmit tokens over HTTPS to prevent interception.
  • Set the aud and iss claims: These claims specify the intended audience and issuer. Verify them on the server to prevent token substitution across services.
  • Keep secrets in environment variables: Use a tool like dotenv to load secrets from a .env file that is not committed to version control.
  • Use a well-tested library: Don’t roll your own crypto. Use jsonwebtoken or jose which are actively maintained and follow best practices.
  • Implement rate limiting: Protect your login and refresh endpoints from brute-force attacks.
  • Log out properly: For stateless JWTs, logout is tricky. You can maintain a blacklist of revoked tokens in Redis, or simply rely on short expiration times.

Alternatives to JWT

JWT isn’t the only option for authentication in Node.js. Traditional session-based auth uses a random session ID stored in a cookie, with server-side session data (in memory or a database). This is simpler to revoke and doesn’t expose claims to the client. OAuth2 and OpenID Connect are protocols that can use JWTs as access tokens, but they add complexity. For server-to-server communication, API keys might suffice. For SPAs, consider using the Backend-for-Frontend (BFF) pattern with httpOnly cookies, which avoids many JWT pitfalls.

Choose JWT when you need statelessness and microservice compatibility. Choose sessions when you need immediate revocation and simplicity.

How to Implement JWT in Node.js: A Minimal Example

Here’s a minimal flow using the jsonwebtoken library:

  1. Install the library: npm install jsonwebtoken.
  2. On login, create a token: jwt.sign({ userId: user.id }, process.env.JWT_SECRET, { expiresIn: '15m' }).
  3. Send the token to the client. Store it in an httpOnly cookie or in memory (for SPAs).
  4. In your middleware, verify the token: jwt.verify(token, process.env.JWT_SECRET, { algorithms: ['HS256'] }).
  5. Attach the decoded payload to the request object (e.g., req.user) for use in route handlers.

For refresh tokens, generate a random string, store its hash in your database, and issue a new access token when the refresh endpoint is called.

Frequently Asked Questions

Is JWT secure?

JWT is secure if implemented correctly—use strong algorithms, verify signatures, set short expirations, and store tokens safely. The biggest risks come from misuse: storing tokens in localStorage, not verifying the algorithm, or using weak secrets.

Can I log out a JWT?

Stateless JWTs cannot be invalidated before expiration unless you maintain a blacklist. For logout, you can delete the token on the client and optionally add the token’s jti (unique ID) to a blacklist on the server until it expires.

What’s the difference between JWT and OAuth?

JWT is a token format; OAuth is an authorization framework. OAuth can use JWTs as access tokens, but it also defines how tokens are obtained and scopes are managed. JWT alone does not specify how to grant tokens.

Should I use JWT or sessions for my Node.js API?

If you need statelessness and plan to scale horizontally, JWT is a good fit. If you want simple revocation and don’t mind server-side storage, sessions may be easier. Consider your use case and security requirements.

How long should a JWT be valid?

Access tokens should be short-lived—15 minutes to 1 hour. Refresh tokens can last days or weeks, but should be rotated and stored securely. The longer a token lives, the greater the risk if it’s stolen.

What is the ‘none’ algorithm attack?

Some libraries allow the algorithm to be set to ‘none’, which means no signature. If your verification doesn’t explicitly reject ‘none’, an attacker can forge a token with an empty signature. Always specify allowed algorithms.

Related

Formula used
in t | Token lifetime | minutes | 60 | 1
in l | Payload length | chars | 100 | 0
out size | Approx token size | bytes | 100 + l + 32 | 0

Each line is one input (in, sel, list) or one result (out: label, unit, formula, decimals). How the calculators work

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.