Authentication

AxilJS JWT Authentication: Token Signing and Verification

Sign and verify JSON Web Tokens with AxilJS using HMAC-SHA256, expiration settings, and constant-time signature comparison.

2 min readDocumentationEdit this page

JWT Authentication

AxilJS provides a JWT utility for signing and verifying JSON Web Tokens using HMAC-SHA256.

JWTs can be used to represent authenticated user information and securely transfer claims between your application components.

Setup

Import JWT from @axiljs/auth and initialize it with a secret.

typescript
import { JWT } from '@axiljs/auth'
 
const jwt = new JWT(
  process.env.JWT_SECRET
) // min 32 chars

The JWT secret should be at least 32 characters long. Store the secret securely in an environment variable rather than directly in application source code.

Sign a Token

Use jwt.sign() to create a signed JWT containing application claims.

typescript
const token = jwt.sign(
  {
    sub: String(user.id),
    role: 'admin'
  },
  {
    expiresIn: '7d'
  }
)

The payload in this example contains:

  • sub — the subject identifier, representing the user ID.
  • role — an application-specific authorization claim.
  • expiresIn — controls how long the generated token remains valid.

The resulting token can be returned to an authenticated client and subsequently presented when accessing protected resources.

Verify a Token

Use jwt.verify() to verify a token and retrieve its payload.

typescript
const payload = jwt.verify(token)

Verification validates the token signature and returns the decoded payload when the token is valid.

Applications should perform JWT verification before trusting claims such as user identifiers or roles.

Token Expiration

AxilJS supports human-readable expiration formats as well as numeric seconds.

Supported examples include:

text
1h
7d
30m

You can also provide the expiration as a number representing seconds.

For example:

typescript
const token = jwt.sign(
  { sub: String(user.id) },
  { expiresIn: '1h' }
)

Shorter expiration periods can be useful for tokens that should have a limited lifetime.

JWT Security

JWT signature verification uses constant-time comparison to reduce the risk of timing attacks.

Warning

Signature comparison uses constant-time comparison to prevent timing attacks.

Keep the JWT secret private and use a sufficiently strong secret in production. Never expose the signing secret to browser-side code or commit it to source control.

Help improve the documentation

AxilJS is open source and documentation improvements are welcome.

AxilJS DocumentationMIT License · Built by SyntaxilitY