Mastering JWT: How to Implement Secure Token Authentication in Node.js

This article explains why session management is needed, compares cookies, sessions and JWT, describes JWT's structure and workflow, and provides a complete Node.js/Koa implementation with code examples and a discussion of its advantages and drawbacks.

Tencent IMWeb Frontend Team
Tencent IMWeb Frontend Team
Tencent IMWeb Frontend Team
Mastering JWT: How to Implement Secure Token Authentication in Node.js

Why Session Management is Needed

HTTP is a stateless protocol; to control user permissions we need mechanisms such as cookies, sessions, and JWT.

Session and Cookie

Session IDs are stored in cookies, while the server keeps the corresponding state. This approach has scalability, cross‑domain, and security limitations.

Cookies are vulnerable to CSRF attacks and can cause cross‑domain issues.

Session data resides on the server; scaling requires shared storage, making horizontal scaling difficult.

What is JWT

JWT (JSON Web Token) solves the problems of sessions by keeping the server stateless; it is especially suitable for authorization scenarios.

JWT Principle

After authentication the server creates a JSON object, signs it, and returns it to the client. The client includes this token with each subsequent request.

{
  "name": "Zhang San",
  "role": "admin",
  "exp": "2018-07-01 00:00"
}

JWT Workflow

Browser sends a login request with username and password.

Server validates credentials, creates a token (header + payload) and signs it.

Server returns the JWT; it should not contain sensitive information.

Client includes the token in the Authorization header (Bearer <token>) for later requests.

Server verifies the token, re‑signs the payload, and grants access if the signature matches.

Token can contain an expiration time; the client must re‑authenticate after it expires.

JWT Structure

JWT consists of three Base64URL‑encoded parts separated by dots: header, payload, and signature.

Header example:

{
  "alg": "HS256",
  "typ": "JWT"
}

Payload contains standard claims such as iss, exp, sub, aud, nbf, iat, jti and can include custom fields.

Signature is generated with HMAC‑SHA256 over base64UrlEncode(header) + "." + base64UrlEncode(payload) using a secret.

Using JWT in a Koa Project

Install jwt-simple or jsonwebtoken and create /login and /validate endpoints.

let Koa = require('koa');
let Router = require('koa-router');
let bodyparser = require('koa-bodyparser');
let jwt = require('jwt-simple');
let router = new Router();
let app = new Koa();
app.use(bodyparser());

let secret = 'zhenglei';

router.post('/login', async ctx => {
  const {username, password} = ctx.request.body;
  if (username === 'admin' && password === 'admin') {
    const token = jwt.encode(username, secret);
    ctx.body = {code: 200, username, token};
  }
});

router.get('/validate', async ctx => {
  const auth = ctx.get('authorization');
  const [, token] = auth.split(' ');
  try {
    const user = jwt.decode(token, secret);
    ctx.body = {code: 200, username: user, token};
  } catch (e) {
    ctx.body = {code: 401, data: 'Not logged in'};
  }
});

app.use(router.routes());
app.listen(4000);

Pros and Cons of JWT

Stateless and easy to scale; can be used for authentication and information exchange.

Not encrypted by default, so sensitive data should not be placed in the token.

Cannot be revoked before expiration; long‑lived tokens increase security risk.

If a token is compromised, all permissions are exposed; use short expiration times and always transmit over HTTPS.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Node.jsAuthenticationJWTTokenKoa
Tencent IMWeb Frontend Team
Written by

Tencent IMWeb Frontend Team

IMWeb Frontend Community gathering frontend development enthusiasts. Follow us for refined live courses by top experts, cutting‑edge technical posts, and to sharpen your frontend skills.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.