JWTAuth
Built-in JWT authentication helper for Gluonic sync servers.
Import
import { JWTAuth } from '@gluonic/auth-jwt'Signature
function JWTAuth(config: JWTAuthConfig): AuthFunctionParameters
config: JWTAuthConfig
| Property | Type | Required | Default | Description |
|---|---|---|---|---|
secret | string | Yes | - | JWT secret key for signing/verifying |
expiresIn | string | No | '7d' | Token expiration time |
algorithm | string | No | 'HS256' | JWT algorithm |
getUserId | (decoded) => string | No | decoded.userId | Extract user ID from decoded token |
Returns
AuthFunction
Authentication function compatible with SyncServer:
type AuthFunction = (req: FastifyRequest) => Promise<void> | voidBehavior:
- 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
- SyncServer - Server configuration
- Authentication Guide - Auth patterns
- Authentication Guide - OAuth, sessions, API keys
Last updated on