Skip to content

Instantly share code, notes, and snippets.

@1mehdifaraji
Last active November 11, 2023 03:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 1mehdifaraji/d32d4da28871fb301697fc6ce131fa05 to your computer and use it in GitHub Desktop.
Save 1mehdifaraji/d32d4da28871fb301697fc6ce131fa05 to your computer and use it in GitHub Desktop.
Jsonwebtoken jwt token generation and verification with express js framework
import { RequestHandler } from "express";
import jwt, { Secret } from "jsonwebtoken";
import { errors } from "@util/locale/errors";
export const generateToken = (userId: string) =>
jwt.sign(userId, process.env.SECRET as Secret);
export const verifyToken = (async (req, res, next) => {
const bearerHeader = req.headers["authorization"] as string;
if (!bearerHeader) {
const err: Error = new Error(errors.authentication.tokenNotProvided);
err.statusCode = 500;
next(err);
} else {
const bearer = bearerHeader.split(" ");
const bearerToken = bearer[1];
try {
jwt.verify(bearerToken, process.env.SECRET as Secret);
next();
} catch (e) {
const err: Error = new Error(errors.authentication.tokenNotVerified);
err.statusCode = 500;
next(err);
}
}
}) as RequestHandler;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment