Skip to content

Instantly share code, notes, and snippets.

@Lyokolux
Last active September 25, 2022 06:44
Show Gist options
  • Save Lyokolux/04498da4652f25cc2ac29f64422a0388 to your computer and use it in GitHub Desktop.
Save Lyokolux/04498da4652f25cc2ac29f64422a0388 to your computer and use it in GitHub Desktop.
An helper function for easy token manipulation based on the package jsonwebtoken.
import jsonwebtoken from "jsonwebtoken"
import type { JwtPayload } from "jsonwebtoken"
export type JwtAppPayload = {
username: string
// more properties to store in the token
}
// augmented type containing the custom informations that
export type JwtApp = JwtPayload & JwtAppPayload
const TOKEN_KEY = 'MY_SECRET_TOKEN_HERE'
const TOKEN_EXPIRATION = '16h'
export const tokenHelper = {
create: (data: JwtPWContent): string => {
return jsonwebtoken.sign({ ...data }, TOKEN_KEY, {
expiresIn: TOKEN_EXPIRATION,
})
},
verify: (token: string): JwtPWPayload | undefined => {
try {
// verify can not return a string (https://github.com/DefinitelyTyped/DefinitelyTyped/discussions/56954)
return jsonwebtoken.verify(token, TOKEN_KEY) as JwtPWPayload | undefined
} catch (error) {
}
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment