JWT Module
The std/jwt module provides JSON Web Token (JWT) signing, verification, and decoding using the HMAC-SHA256 (HS256) algorithm.
Import
Section titled “Import”import { jwt } from "std/jwt"Functions
Section titled “Functions”jwt.sign(payload: map, secret: string, expiresInMs?: int): string
Section titled “jwt.sign(payload: map, secret: string, expiresInMs?: int): string”Sign a payload into a JWT token. Optionally set an expiration time in milliseconds from now.
// Token that never expiresconst token = jwt.sign({ "sub": "user123", "role": "admin" }, "my-secret")
// Token that expires in 1 hourconst token = jwt.sign( { "sub": "user123", "role": "admin" }, "my-secret", 3600000)jwt.verify(token: string, secret: string): map
Section titled “jwt.verify(token: string, secret: string): map”Verify a JWT token’s signature and expiration. Returns the decoded claims map on success, or throws an Error if the token is invalid or expired.
try { const claims = jwt.verify(token, "my-secret") println(claims["sub"]) // "user123" println(claims["role"]) // "admin"} catch (err) { println("Invalid token: " + err.message)}jwt.decode(token: string): map
Section titled “jwt.decode(token: string): map”Decode a JWT without verifying the signature. Returns a map with header and payload keys.
const parts = jwt.decode(token)println(parts["header"]) // { "alg": "HS256", "typ": "JWT" }println(parts["payload"]) // { "sub": "user123", ... }Function Reference
Section titled “Function Reference”| Function | Description |
|---|---|
jwt.sign(payload, secret, expiresMs?) | Sign a payload into a JWT string |
jwt.verify(token, secret) | Verify and decode a JWT (throws on fail) |
jwt.decode(token) | Decode without verification |
Example: Auth Middleware
Section titled “Example: Auth Middleware”import { createServer, Request, Response } from "std/http"import { jwt } from "std/jwt"import { json } from "std/json"
const SECRET = "my-secret-key"const app = createServer()
// Login route — issues a tokenapp.post("/login", function(req: Request, res: Response): Response { const body = json.parse(req.body) // Validate credentials... const token = jwt.sign( { "sub": body["username"], "role": "user" }, SECRET, 3600000 // 1 hour ) return res.json('{"token": "' + token + '"}')})
// Auth middleware — verifies the tokenapp.use(function(req: Request, res: Response, next: any) { if (req.path == "/login") { next() return } const token = req.headers["Authorization"] try { const claims = jwt.verify(token, SECRET) next() } catch (err) { res.status(401).json('{"error": "Unauthorized"}') }})
// Protected routeapp.get("/profile", function(req: Request, res: Response): Response { return res.json('{"message": "Protected data"}')})
app.listen(3000)