open-index/open-npm huggingface dataset:
npm package: @mnabil1718/jwt
Description: JWT generation and verification utilities built on [jose](https://github.com/panva/jose).
Latest version: 1.0.1

# @mnabil1718/jwt

JWT generation and verification utilities built on [jose](https://github.com/panva/jose).

## Installation

```bash
npm install @mnabil1718/jwt
```

## Usage

```typescript
import { createJwtSecret, generateJWT, verifyJWT } from "@mnabil1718/jwt";

const JWT_SECRET = createJwtSecret(process.env.JWT_SECRET!);

// Generate a token
const token = await generateJWT({ sub: "user-123", role: "admin" }, JWT_SECRET);

// Custom expiration (default is 15m)
const token = await generateJWT(
  { sub: "user-123", role: "admin" },
  JWT_SECRET,
  "1h",
);

// Verify a token
const payload = await verifyJWT(token, JWT_SECRET);
console.log(payload.sub); // "user-123"
console.log(payload.role); // "admin"

// Throws AuthenticationError on invalid or expired token
```

## Express Middleware Example

```typescript
import { createJwtSecret, verifyJWT } from "@mnabil1718/jwt";
import { AuthenticationError } from "@mnabil1718/errors";
import { Request, Response, NextFunction } from "express";

const JWT_SECRET = createJwtSecret(process.env.JWT_SECRET!);

export const authenticate = async (
  req: Request,
  res: Response,
  next: NextFunction,
) => {
  const authHeader = req.headers.authorization;

  if (!authHeader?.startsWith("Bearer ")) {
    return next(new AuthenticationError("missing token"));
  }

  const token = authHeader.split(" ")[1];
  const payload = await verifyJWT(token, JWT_SECRET);
  req.user = payload;
  next();
};
```

## API

### `createJwtSecret(secret: string): Uint8Array`

Encodes your secret string into a format jose expects.

### `generateJWT(payload, secret, expirationTime?): Promise<string>`

Signs a JWT with HS256. Expiration defaults to `15m`. Accepts any [jose-compatible duration string](https://github.com/panva/jose/blob/main/docs/types/types.JWTPayload.md) like `1h`, `7d`, `30d`.

### `verifyJWT(jwt, secret): Promise<JwtPayload>`

Verifies and decodes a JWT. Throws `AuthenticationError` if invalid or expired.

## JwtPayload

```typescript
type JwtPayload = {
  sub: string; // user ID (RFC 7519)
  role: string;
};
```