fastify-xauth-local
jwt.verify
Verify a JWT and return the decoded payload, throwing on invalid or expired tokens.
jwt.verify
Verifies a JWT against the config's key (or secret) and algorithm, and returns the decoded payload. Throws if the token is expired, tampered, or otherwise invalid.
Signature
const api = fastify.xauthlocal.get(name: string)
api.jwt.verify(
token: string,
options?: {
audience?: string // Override audience claim to verify against
issuer?: string // Override issuer claim to verify against
}
): Record<string, any>
Params
| Name | Type | Required | Description |
|---|---|---|---|
token | string | Yes | The JWT string to verify |
options.audience | string | No | Override the config's default audience for this call |
options.issuer | string | No | Override the config's default issuer for this call |
Returns
The decoded token payload as a plain object (includes standard claims like iat, exp, sub plus any custom claims from sign).
Throws
Throws a JsonWebTokenError or TokenExpiredError from jsonwebtoken in these cases:
| Error | Message |
|---|---|
| Expired token | jwt expired |
| Bad signature | invalid signature |
| Malformed token | jwt malformed |
| Wrong audience | jwt audience invalid |
| Wrong issuer | jwt issuer invalid |
The auth middleware catches these and replies with 401 Unauthorized automatically. Use verify directly only when you need the payload outside a request context.
Examples
Basic: manually verify a token from a header
const api = fastify.xauthlocal.get("api");
fastify.post("/api/token-inspect", async (request, reply) => {
const authHeader = request.headers.authorization;
const token = authHeader?.replace("Bearer ", "");
if (!token) return reply.code(401).send({ error: "No token" });
try {
const payload = api.jwt.verify(token);
return { valid: true, payload };
} catch (err) {
return reply.code(401).send({ valid: false, error: err.message });
}
});
Advanced: verify with an audience override
const api = fastify.xauthlocal.get("api");
// Validate a short-lived password-reset token
try {
const payload = api.jwt.verify(resetToken, { audience: "password-reset" });
// payload.id is the user to reset
} catch (err) {
throw new Error("Invalid or expired reset link");
}
See Also
- jwt.sign — create a signed token
- jwt.decode — inspect a token without verification
AI Context
package: "@xenterprises/fastify-xauth-local"
method: fastify.xauthlocal.get('name').jwt.verify(token)
use-when: Verify a JWT and return the decoded payload — throws on invalid/expired token
returns: decoded payload object
