---
name: azion-sign-and-verify-a-jwt-with-azion-lib
description: >-
  Sign a JSON Web Token with a shared secret, verify it, and reject a token with the wrong signature or a past expiration, with the @aziontech/jwt package.
---

# Sign and verify a JWT with Azion Lib

You can sign a JSON Web Token (JWT) with a shared secret and verify it later, with the `@aziontech/jwt` package of [Azion Lib](/en/documentation/devtools/azion-lib/). The examples run in Node.js, sign with the default `HS256` algorithm, and need no Azion account or personal token. To sign with a key pair instead, refer to [Keys and algorithms](/en/documentation/devtools/azion-lib/jwt/#keys-and-algorithms).

---

## Prerequisites

- Node.js and npm. The script is an ES module that uses top-level `await`.
- A secret to sign the tokens with, kept out of your code. The examples read it from the `JWT_SECRET` environment variable.

---

## Install the package

The script imports `@aziontech/jwt` from the `node_modules` directory of its project.

In an empty directory, create the project and install the package:

```bash
npm init -y
npm install @aziontech/jwt
```

npm prints the new `package.json`, and the install ends with:

```text
added 1 package, and audited 2 packages in 2s

found 0 vulnerabilities
```

The project has `@aziontech/jwt` in its `package.json` dependencies.

---

## Write the token script

The script runs one of three functions of the package, named by its first argument:

- With `sign`, the script calls [`sign`](/en/documentation/devtools/azion-lib/jwt/#sign-a-token). The `sub` claim is the value you pass. The third argument sets `exp` in whole seconds from now, `3600` by default.
- With `verify`, the script calls [`verify`](/en/documentation/devtools/azion-lib/jwt/#verify-a-token), which checks the signature and the time claims and returns the payload.
- With `decode`, the script calls [`decode`](/en/documentation/devtools/azion-lib/jwt/#decode-a-token), which reads the claims without checking the signature.

`verify` rejects an invalid token with an error. The script prints the error's `name`, such as `JwtTokenExpired`, because the package does not export the error classes. For every error name, refer to [Errors](/en/documentation/devtools/azion-lib/jwt/#errors).

Create a `token.mjs` file:

```javascript
import { decode, sign, verify } from '@aziontech/jwt';

const secret = process.env.JWT_SECRET;
if (!secret) {
  console.error('Set the JWT_SECRET variable first');
  process.exit(1);
}
const [command, value, ttl = '3600'] = process.argv.slice(2);

if (command === 'sign') {
  const now = Math.floor(Date.now() / 1000);
  const token = await sign({ sub: value, iat: now, exp: now + Number(ttl) }, secret);
  console.log(token);
} else if (command === 'verify') {
  try {
    const payload = await verify(value, secret);
    console.log('valid', payload);
  } catch (err) {
    console.error('invalid', err.name);
    process.exit(1);
  }
} else if (command === 'decode') {
  const { header, payload } = decode(value);
  console.log(header, payload);
}
```

Without `JWT_SECRET`, the script prints `Set the JWT_SECRET variable first` and exits with code `1`. The check exists because `sign`, called with no secret, fails with a `TypeError` instead of a named error.

---

## Sign a token

The script reads the secret from `JWT_SECRET`, so the secret stays out of the script's code.

To sign a token:

1. Store your secret in the `JWT_SECRET` variable. Replace `[TOKEN VALUE]` with your secret:

   ```bash
   export JWT_SECRET=[TOKEN VALUE]
   ```

   Every script you start from this terminal reads the secret, until the terminal closes.

2. Sign a token for the subject `user-42` that expires in one hour, and store it in the `TOKEN` variable:

   ```bash
   TOKEN=$(node token.mjs sign user-42)
   echo $TOKEN
   ```

   ```text
   eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyLTQyIiwiaWF0IjoxNzk1MDE1MDM2LCJleHAiOjE3OTUwMTg2MzZ9.t3cTNN4fokGaviVPcrxFJkP6mjzs0OcXaKfCZhwYSeA
   ```

`TOKEN` holds a signed token. Its characters differ from the example, because the payload carries the current time and your secret signs it.

---

## Verify a token

`verify` returns the payload only when the signature matches the secret and no time claim fails. An `exp` in the past, or an `nbf` or `iat` in the future, rejects the token. A token with no `exp` claim never expires, so the script always sets one.

To verify a token with the secret that signed it:

1. Store your secret in the `JWT_SECRET` variable. Replace `[TOKEN VALUE]` with your secret:

   ```bash
   export JWT_SECRET=[TOKEN VALUE]
   ```

2. Sign a token for the subject `user-42`, and store it in the `TOKEN` variable:

   ```bash
   TOKEN=$(node token.mjs sign user-42)
   ```

   `TOKEN` holds a token that your secret signed.

3. Verify the token:

   ```bash
   node token.mjs verify $TOKEN
   ```

   ```text
   valid { sub: 'user-42', iat: 1795015036, exp: 1795018636 }
   ```

The token is valid, and the script prints its claims. Times are Unix timestamps, in seconds.

---

## Reject an invalid token

Two tokens fail the check: one that another secret signed, and one whose `exp` claim is in the past. In both cases the script prints `invalid` with the error name and exits with code `1`.

To see both rejections:

1. Store your secret in the `JWT_SECRET` variable. Replace `[TOKEN VALUE]` with your secret:

   ```bash
   export JWT_SECRET=[TOKEN VALUE]
   ```

2. Sign a token for the subject `user-42`, and store it in the `TOKEN` variable:

   ```bash
   TOKEN=$(node token.mjs sign user-42)
   ```

   `TOKEN` holds a token that your secret signed.

3. Verify the token with a different secret:

   ```bash
   JWT_SECRET=another-secret node token.mjs verify $TOKEN
   ```

   ```text
   invalid JwtTokenSignatureMismatched
   ```

4. Sign a token that expired 60 seconds ago, and store it in the `EXPIRED` variable:

   ```bash
   EXPIRED=$(node token.mjs sign user-42 -60)
   ```

   `EXPIRED` holds a token whose `exp` claim is in the past.

5. Verify the expired token:

   ```bash
   node token.mjs verify $EXPIRED
   ```

   ```text
   invalid JwtTokenExpired
   ```

The script rejects a token that another secret signed and a token that has expired.

---

## Read the claims without verifying

`decode` reads the header and the claims of any token, including an expired one. It checks neither the signature nor the time claims. Use it to inspect a token, never to trust one.

To read the claims of an expired token:

1. Store your secret in the `JWT_SECRET` variable. Replace `[TOKEN VALUE]` with your secret:

   ```bash
   export JWT_SECRET=[TOKEN VALUE]
   ```

2. Sign a token that expired 60 seconds ago, and store it in the `EXPIRED` variable:

   ```bash
   EXPIRED=$(node token.mjs sign user-42 -60)
   ```

   `EXPIRED` holds a token whose `exp` claim is in the past.

3. Decode the token:

   ```bash
   node token.mjs decode $EXPIRED
   ```

   ```text
   { alg: 'HS256', typ: 'JWT' } { sub: 'user-42', iat: 1795015036, exp: 1795014976 }
   ```

The output shows the algorithm that the token header names, and an `exp` earlier than `iat`.

---

## Next steps

- [Azion Lib JWT](/en/documentation/devtools/azion-lib/jwt.md): Every function of @aziontech/jwt, the 13 algorithms, and the seven error names.
- [SubtleCrypto](/en/documentation/devtools/runtime/api-reference/subtle-crypto.md): The crypto.subtle methods of Azion Runtime, such as generateKey for the Elliptic Curve Digital Signature Algorithm (ECDSA) P-256 key pair that ES256 signs with.
