Generate JWT Access Tokens

After successful authentication, generate an access token for the user.

The token should contain only the claims needed by the API.

We will use:

  • sub: User ID.
  • iss: Token issuer.
  • aud: Intended audience.
  • exp: Expiration.

Create a token utility inside src/utils.

The token secret must come from environment configuration.

Token Expiration

Short-lived access tokens reduce the impact of token theft. A production application may also implement refresh token rotation and revocation.

src/utils/jwt.js
import jwt from 'jsonwebtoken';

export function generateAccessToken(user) {
  if (!process.env.JWT_SECRET) {
    throw new Error('JWT_SECRET is not configured');
  }

  return jwt.sign(
    {},
    process.env.JWT_SECRET,
    {
      algorithm: 'HS256',
      subject: user._id.toString(),
      issuer: 'rest-api',
      audience: 'rest-api-client',
      expiresIn: process.env.JWT_EXPIRES_IN || '15m'
    }
  );
}

Generates a signed JWT with a user subject, issuer, audience, algorithm, and expiration.

Key Takeaways
  • JWT signing creates a verifiable access token.

  • Use explicit algorithm, issuer, audience, and expiration settings.

  • Never expose the signing secret.