View as Json

JWT Utils

JWT signing/verifying helpers (access + refresh) for Next.js templates.

Installation Guide

Install the component using the servercn CLI:

npx servercn-cli@latest add jwt-utils

Usage Example

Example (Next.js Route Handler):

import { NextResponse } from "next/server";
import {
  extractTokenFromHeader,
  verifyAccessToken,
  JwtExpiredError,
  JwtInvalidError
} from "@/lib/jwt";
 
export async function GET(req: Request) {
  const token = extractTokenFromHeader(
    req.headers.get("authorization") ?? undefined
  );
  if (!token)
    return NextResponse.json(
      { error: "Missing bearer token" },
      { status: 401 }
    );
 
  try {
    const payload = verifyAccessToken(token);
    return NextResponse.json({
      userId: payload.sub,
      email: payload.email,
      sid: payload.sid
    });
  } catch (err) {
    if (err instanceof JwtExpiredError) {
      return NextResponse.json(
        { error: "Access token expired" },
        { status: 401 }
      );
    }
    if (err instanceof JwtInvalidError) {
      return NextResponse.json(
        { error: "Invalid access token" },
        { status: 401 }
      );
    }
    return NextResponse.json({ error: "Auth error" }, { status: 401 });
  }
}
 

File & Folder Structure

Loading files...

Installation

npx servercn-cli@latest add jwt-utils