Skip to Content

JWTAuth

Built-in JWT authentication helper for Gluonic sync servers.

Import

import { JWTAuth } from '@gluonic/auth-jwt'

Signature

function JWTAuth(config: JWTAuthConfig): AuthFunction

Parameters

config: JWTAuthConfig

PropertyTypeRequiredDefaultDescription
secretstringYes-JWT secret key for signing/verifying
expiresInstringNo'7d'Token expiration time
algorithmstringNo'HS256'JWT algorithm
getUserId(decoded) => stringNodecoded.userIdExtract user ID from decoded token

Returns

AuthFunction

Authentication function compatible with SyncServer:

type AuthFunction = (req: FastifyRequest) => Promise<void> | void

Behavior:

  • Extracts token from Authorization: Bearer {token} header
  • For WebSocket: Also checks query param ?token={token}
  • Verifies JWT signature
  • Attaches decoded user to req.user
  • Throws error if invalid/missing

Examples

Basic Usage

import { JWTAuth } from '@gluonic/auth-jwt' const server = SyncServer({ database, auth: JWTAuth({ secret: process.env.JWT_SECRET }) })

Custom Expiration

const server = SyncServer({ database, auth: JWTAuth({ secret: process.env.JWT_SECRET, expiresIn: '30d' // 30 days }) })

Custom User ID Extraction

const server = SyncServer({ database, auth: JWTAuth({ secret: process.env.JWT_SECRET, getUserId: (decoded) => decoded.sub // Use 'sub' claim instead of 'userId' }) })

Creating Tokens

JWTAuth verifies tokens - you create them in your auth endpoints:

import jwt from 'jsonwebtoken' // Sign in endpoint app.post('/auth/signin', async (req, reply) => { const { email, password } = req.body // Verify credentials const user = await verifyCredentials(email, password) // Create JWT const token = jwt.sign( { userId: user.id, email: user.email }, process.env.JWT_SECRET, { expiresIn: '7d' } ) reply.send({ token, user }) })

For Custom Auth

If you need OAuth, sessions, or API keys, see the Authentication guide for patterns.

See Also

Last updated on