Skip to content

Instantly share code, notes, and snippets.

@mallendeo
Created October 4, 2023 15:22
Show Gist options
  • Save mallendeo/a848eab32227d6d54087733a27013891 to your computer and use it in GitHub Desktop.
Save mallendeo/a848eab32227d6d54087733a27013891 to your computer and use it in GitHub Desktop.
Sign JWT using Jose
import * as jose from 'jose'
const JWT_SECRET = new TextEncoder().encode(ENV.JWT_SECRET)
export const signJWT = async (
data: Record<any, any>,
opts?: {
iat?: number
exp?: string | number
},
) => {
const alg = 'HS256'
const jwt = await new jose.SignJWT(data)
.setProtectedHeader({ alg })
.setIssuedAt(opts?.iat)
.setIssuer('example.app')
.setAudience('example.app')
.setExpirationTime(opts?.exp || '1h')
.sign(JWT_SECRET)
return jwt
}
export const verifyJWT = async (jwt: string) => {
const { payload } = await jose.jwtVerify(jwt, JWT_SECRET, {
issuer: 'example.app',
audience: 'example.app',
})
return payload
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment