Yes, Express JS server routes can be used to handleuser login authentication using JSON Web Tokens (JWT). Here is an example of a login route that uses JWT authentication:
JavaScript
const express = require("express");
const jwt = require("jsonwebtoken");
const app = express();
const SECRET_KEY = "my-secret-key";
app.post("/login", (req, res) => {
const { email, password } = req.body;
// Check if the user exists and the password is correct.
if (email === "johndoe@example.com" && password === "password") {
// Create a JWT token.
const token = jwt.sign({ email }, SECRET_KEY, { expiresIn: "1h" });
// Return the token to the client.
res.json({ token });
} else {
// Return an error message.
res.status(401).json({ error: "Invalid credentials" });
}
});
app.listen(3000);
This route first checks if the user exists and the password is correct. If the user credentials are valid, a JWT token is created and returned to the client. The JWT token can then be used to authenticate the user on subsequent requests.
The SECRET_KEY constant is a secret key that is used to sign the JWT token. This key should be kept secret and should not be shared with anyone.
The expiresIn option specifies how long the JWT token will be valid for. In this example, the token will expire after 1 hour.
The jsonwebtoken module is used to create and verify JWT tokens. This module is available as a package on npm.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Yes, Express JS server routes can be used to handle user login authentication using JSON Web Tokens (JWT). Here is an example of a login route that uses JWT authentication:
JavaScript
This route first checks if the user exists and the password is correct. If the user credentials are valid, a JWT token is created and returned to the client. The JWT token can then be used to authenticate the user on subsequent requests.
The
SECRET_KEYconstant is a secret key that is used to sign the JWT token. This key should be kept secret and should not be shared with anyone.The
expiresInoption specifies how long the JWT token will be valid for. In this example, the token will expire after 1 hour.The
jsonwebtokenmodule is used to create and verify JWT tokens. This module is available as a package on npm.