Skip to content

JWT Module

The std/jwt module provides JSON Web Token (JWT) signing, verification, and decoding using the HMAC-SHA256 (HS256) algorithm.

import { jwt } from "std/jwt"

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 expires
const token = jwt.sign({ "sub": "user123", "role": "admin" }, "my-secret")
// Token that expires in 1 hour
const 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)
}

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", ... }
FunctionDescription
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
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 token
app.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 token
app.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 route
app.get("/profile", function(req: Request, res: Response): Response {
return res.json('{"message": "Protected data"}')
})
app.listen(3000)