{"id":150478,"date":"2026-12-03T13:00:20","date_gmt":"2026-12-03T07:30:20","guid":{"rendered":"https:\/\/www.guvi.in\/blog\/?p=150478"},"modified":"2026-12-03T13:00:23","modified_gmt":"2026-12-03T07:30:23","slug":"jwt-authentication-tutorial","status":"publish","type":"post","link":"https:\/\/www.guvi.in\/blog\/jwt-authentication-tutorial\/","title":{"rendered":"JWT Authentication Tutorial: Build a Secure Login System in Node.js"},"content":{"rendered":"\n<p>Every REST API that handles user data has to answer one question on each request: who is calling, and are they allowed in? HTTP is stateless, so the server does not remember a login between requests. Token-based authentication fixes this by handing the client a signed token at login and verifying it on every call after that.<\/p>\n\n\n\n<p>JSON Web Tokens (JWT) are the most widely used way to do this in Node.js APIs. This JWT authentication tutorial walks you through building a secure login system with Express.js, MongoDB, bcrypt and the jsonwebtoken library. You will register users, hash passwords, issue access and refresh tokens, protect routes with middleware, and test every case in Postman.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>TL;DR<\/strong><\/h2>\n\n\n\n<ul>\n<li>A JWT is a signed token with three parts: header, payload and signature. The server verifies it without a session lookup.<\/li>\n\n\n\n<li>The login flow is: verify credentials, sign a token, return it, then validate it on every protected request.<\/li>\n\n\n\n<li>Use short-lived access tokens (about 15 minutes) and longer-lived refresh tokens that can be rotated and revoked.<\/li>\n\n\n\n<li>Hash passwords with bcrypt, keep secrets in environment variables, and never put sensitive data in the payload.<\/li>\n\n\n\n<li>Serve everything over HTTPS and rate-limit login endpoints.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>What Is JWT Authentication?<\/strong><\/h2>\n\n\n\n<p>A JSON Web Token is a compact, URL-safe string that carries claims about a user and is signed by the server. Because the signature proves the token has not been altered, the API can trust its contents without querying a session store. That is why JWT token authentication suits stateless REST APIs and horizontally scaled services.<\/p>\n\n\n\n<p>This JSON Web Token tutorial starts with the structure. Every JWT has three Base64URL-encoded parts separated by dots:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>xxxxx.yyyyy.zzzzz\n\nheader.payload.signature<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Header<\/strong><\/h3>\n\n\n\n<p>Describes the token type and the signing algorithm, for example { &#8220;alg&#8221;: &#8220;HS256&#8221;, &#8220;typ&#8221;: &#8220;JWT&#8221; }.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Payload<\/strong><\/h3>\n\n\n\n<p>Holds the claims: the user ID (sub or a custom id), the issue time (iat) and the expiry (exp). The payload is encoded, not encrypted, so anyone holding the token can read it.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Signature<\/strong><\/h3>\n\n\n\n<p>The server signs the encoded header and payload with a secret key. If anyone changes a single character, verification fails.<\/p>\n\n\n\n<p><em><strong>Ready to take your full-stack development skills to the next level?<\/strong> Enrol in our comprehensive <a href=\"https:\/\/www.guvi.in\/zen-class\/full-stack-development-course\/?utm_source=blog&amp;utm_medium=hyperlink&amp;utm_campaign=jwt-authentication-tutorial\" target=\"_blank\" rel=\"noreferrer noopener\">Full-Stack Development Course<\/a> and master both front-end and back-end development. Gain hands-on experience with Java, Spring Boot, Hibernate, Angular, and React while learning to build secure, scalable, and dynamic web applications. Develop practical skills through real-world projects and prepare yourself for exciting full-stack development opportunities. Start learning today!<\/em><\/p>\n\n\n<div class=\"wp-block-guvi-cta-button\" style=\"justify-content:center;\"><a href=\"https:\/\/www.guvi.in\/zen-class\/full-stack-development-course\/?utm_source=blog&#038;utm_medium=cta_button&#038;utm_campaign=jwt-authentication-tutorial\" class=\"guvi-btn-enquire\" target=\"_blank\" rel=\"noopener noreferrer\">Enquire Now<\/a><\/div>\n\n\n<h2 class=\"wp-block-heading\"><strong>How JWT Authentication Works in a REST API<\/strong><\/h2>\n\n\n\n<p>The flow has six steps:<\/p>\n\n\n\n<ol>\n<li>The user submits an email and password to the login endpoint.<\/li>\n\n\n\n<li>The server looks up the user and compares the password with the stored hash.<\/li>\n\n\n\n<li>If it matches, the server signs a <a href=\"https:\/\/www.jwt.io\/\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">JWT<\/a> containing the user&#8217;s ID.<\/li>\n\n\n\n<li>The client receives the token and stores it.<\/li>\n\n\n\n<li>The client sends the token in the Authorization: Bearer &lt;token&gt; header on later requests.<\/li>\n\n\n\n<li>The server verifies the signature and expiry before it grants access.<\/li>\n<\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>Client&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Server\n\n&nbsp;&nbsp;| -- POST \/login (email, password) --&gt;&nbsp; |&nbsp; verify password hash\n\n&nbsp;&nbsp;| &lt;-- 200 { accessToken, refreshToken } |&nbsp; sign JWT\n\n&nbsp;&nbsp;| &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; |\n\n&nbsp;&nbsp;| -- GET \/profile &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; |\n\n&nbsp;&nbsp;|&nbsp; &nbsp; Authorization: Bearer &lt;token&gt; ---&gt; |&nbsp; verify signature + expiry\n\n&nbsp;&nbsp;| &lt;-- 200 { user data }&nbsp; -------------- |&nbsp; (or 401 if invalid)<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Prerequisites and Project Setup<\/strong><\/h2>\n\n\n\n<p>You need basic <a href=\"https:\/\/www.guvi.in\/hub\/javascript\/what-is-javascript\/\" target=\"_blank\" rel=\"noreferrer noopener\">JavaScript <\/a>and REST API knowledge, plus these tools:<\/p>\n\n\n\n<ul>\n<li><strong>Node.js<\/strong> (v18 or later) and <strong>Express.js<\/strong> for the server<\/li>\n\n\n\n<li><strong>MongoDB<\/strong> (local or Atlas) with <strong>Mongoose<\/strong> for data modelling<\/li>\n\n\n\n<li><strong>jsonwebtoken<\/strong> to sign and verify tokens<\/li>\n\n\n\n<li><strong>bcryptjs<\/strong> to hash passwords<\/li>\n\n\n\n<li><strong>dotenv<\/strong> to load environment variables<\/li>\n\n\n\n<li><strong>Postman<\/strong> to test the endpoints<\/li>\n<\/ul>\n\n\n\n<p>Create the project and install the dependencies:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>mkdir jwt-auth-demo &amp;&amp; cd jwt-auth-demo\n\nnpm init -y\n\nnpm install express mongoose jsonwebtoken bcryptjs dotenv\n\nnpm install --save-dev nodemon<\/code><\/pre>\n\n\n\n<p>Use this structure:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>jwt-auth-demo\/\n\n\u251c\u2500\u2500 models\/User.js\n\n\u251c\u2500\u2500 middleware\/auth.js\n\n\u251c\u2500\u2500 routes\/auth.js\n\n\u251c\u2500\u2500 .env\n\n\u2514\u2500\u2500 server.js<\/code><\/pre>\n\n\n\n<p>Add your secrets to .env, and keep this file out of version control:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>PORT=5000\n\nMONGO_URI=mongodb:\/\/127.0.0.1:27017\/jwt_auth_demo\n\nJWT_ACCESS_SECRET=replace_with_a_long_random_string\n\nJWT_REFRESH_SECRET=replace_with_a_different_long_random_string<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Build JWT Authentication in Node.js<\/strong><\/h2>\n\n\n\n<p>The snippets below form one working application. Create each file as shown.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Step 1: Create the Express server and connect MongoDB<\/strong><\/h3>\n\n\n\n<p>server.js loads the environment variables, connects to MongoDB, mounts the auth routes and exposes one protected route. The server starts only after the database connection succeeds.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ server.js\n\nrequire(\"dotenv\").config();\n\nconst express = require(\"express\");\n\nconst mongoose = require(\"mongoose\");\n\nconst authRoutes = require(\".\/routes\/auth\");\n\nconst auth = require(\".\/middleware\/auth\");\n\nconst app = express();\n\napp.use(express.json());\n\napp.use(\"\/api\/auth\", authRoutes);\n\napp.get(\"\/api\/profile\", auth, (req, res) =&gt; {\n\n&nbsp;&nbsp;res.json({ message: \"Protected data\", userId: req.user.id });\n\n});\n\nmongoose\n\n&nbsp;&nbsp;.connect(process.env.MONGO_URI)\n\n&nbsp;&nbsp;.then(() =&gt; {\n\n&nbsp;&nbsp;&nbsp;&nbsp;console.log(\"MongoDB connected\");\n\n&nbsp;&nbsp;&nbsp;&nbsp;app.listen(process.env.PORT, () =&gt;\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;console.log(`Server running on port ${process.env.PORT}`)\n\n&nbsp;&nbsp;&nbsp;&nbsp;);\n\n&nbsp;&nbsp;})\n\n&nbsp;&nbsp;.catch((err) =&gt; {\n\n&nbsp;&nbsp;&nbsp;&nbsp;console.error(\"Database connection failed:\", err.message);\n\n&nbsp;&nbsp;&nbsp;&nbsp;process.exit(1);\n\n&nbsp;&nbsp;});<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Step 2: Create the user model and hash passwords<\/strong><\/h3>\n\n\n\n<p>The schema stores a refreshTokens array, which the refresh flow later uses for rotation and revocation. The pre(&#8220;save&#8221;) hook hashes the password with bcrypt (12 salt rounds) whenever it changes, so plain-text passwords never reach the database.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ models\/User.js\n\nconst mongoose = require(\"mongoose\");\n\nconst bcrypt = require(\"bcryptjs\");\n\nconst userSchema = new mongoose.Schema({\n\n&nbsp;&nbsp;name: { type: String, required: true, trim: true },\n\n&nbsp;&nbsp;email: { type: String, required: true, unique: true, lowercase: true, trim: true },\n\n&nbsp;&nbsp;password: { type: String, required: true, minlength: 8 },\n\n&nbsp;&nbsp;refreshTokens: &#91;String],\n\n});\n\nuserSchema.pre(\"save\", async function () {\n\n&nbsp;&nbsp;if (!this.isModified(\"password\")) return;\n\n&nbsp;&nbsp;this.password = await bcrypt.hash(this.password, 12);\n\n});\n\nuserSchema.methods.matchPassword = function (plainPassword) {\n\n&nbsp;&nbsp;return bcrypt.compare(plainPassword, this.password);\n\n};\n\nmodule.exports = mongoose.model(\"User\", userSchema);<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Step 3: Implement registration, login and token generation<\/strong><\/h3>\n\n\n\n<p>The routes file handles four things. \/register creates a user, and the model hook hashes the password. \/login checks the password and returns an access token and a refresh token. \/refresh swaps a valid refresh token for a new pair. \/logout revokes the refresh token.<\/p>\n\n\n\n<p>Both login failures return the same message. That stops attackers from learning which emails are registered. Each refresh token also gets a unique jwtid, so two tokens issued in the same second are never identical.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ routes\/auth.js\n\nconst express = require(\"express\");\n\nconst jwt = require(\"jsonwebtoken\");\n\nconst { randomUUID } = require(\"crypto\");\n\nconst User = require(\"..\/models\/User\");\n\nconst router = express.Router();\n\nconst signAccessToken = (id) =&gt;\n\n&nbsp;&nbsp;jwt.sign({ id }, process.env.JWT_ACCESS_SECRET, { expiresIn: \"15m\" });\n\nconst signRefreshToken = (id) =&gt;\n\n&nbsp;&nbsp;jwt.sign({ id }, process.env.JWT_REFRESH_SECRET, {\n\n&nbsp;&nbsp;&nbsp;&nbsp;expiresIn: \"7d\",\n\n&nbsp;&nbsp;&nbsp;&nbsp;jwtid: randomUUID(),\n\n&nbsp;&nbsp;});\n\nrouter.post(\"\/register\", async (req, res) =&gt; {\n\n&nbsp;&nbsp;try {\n\n&nbsp;&nbsp;&nbsp;&nbsp;const { name, email, password } = req.body;\n\n&nbsp;&nbsp;&nbsp;&nbsp;if (await User.findOne({ email })) {\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return res.status(409).json({ message: \"Email already registered\" });\n\n&nbsp;&nbsp;&nbsp;&nbsp;}\n\n&nbsp;&nbsp;&nbsp;&nbsp;const user = await User.create({ name, email, password });\n\n&nbsp;&nbsp;&nbsp;&nbsp;res.status(201).json({ id: user.id, name: user.name, email: user.email });\n\n&nbsp;&nbsp;} catch (err) {\n\n&nbsp;&nbsp;&nbsp;&nbsp;res.status(400).json({ message: err.message });\n\n&nbsp;&nbsp;}\n\n});\n\nrouter.post(\"\/login\", async (req, res) =&gt; {\n\n&nbsp;&nbsp;try {\n\n&nbsp;&nbsp;&nbsp;&nbsp;const { email, password } = req.body;\n\n&nbsp;&nbsp;&nbsp;&nbsp;if (!email || !password) {\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return res.status(400).json({ message: \"Email and password are required\" });\n\n&nbsp;&nbsp;&nbsp;&nbsp;}\n\n&nbsp;&nbsp;&nbsp;&nbsp;const user = await User.findOne({ email });\n\n&nbsp;&nbsp;&nbsp;&nbsp;if (!user || !(await user.matchPassword(password))) {\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return res.status(401).json({ message: \"Invalid email or password\" });\n\n&nbsp;&nbsp;&nbsp;&nbsp;}\n\n&nbsp;&nbsp;&nbsp;&nbsp;const accessToken = signAccessToken(user.id);\n\n&nbsp;&nbsp;&nbsp;&nbsp;const refreshToken = signRefreshToken(user.id);\n\n&nbsp;&nbsp;&nbsp;&nbsp;user.refreshTokens.push(refreshToken);\n\n&nbsp;&nbsp;&nbsp;&nbsp;await user.save();\n\n&nbsp;&nbsp;&nbsp;&nbsp;res.json({ accessToken, refreshToken });\n\n&nbsp;&nbsp;} catch (err) {\n\n&nbsp;&nbsp;&nbsp;&nbsp;res.status(500).json({ message: \"Server error\" });\n\n&nbsp;&nbsp;}\n\n});\n\nrouter.post(\"\/refresh\", async (req, res) =&gt; {\n\n&nbsp;&nbsp;const { refreshToken } = req.body;\n\n&nbsp;&nbsp;if (!refreshToken) {\n\n&nbsp;&nbsp;&nbsp;&nbsp;return res.status(400).json({ message: \"Refresh token required\" });\n\n&nbsp;&nbsp;}\n\n&nbsp;&nbsp;try {\n\n&nbsp;&nbsp;&nbsp;&nbsp;const payload = jwt.verify(refreshToken, process.env.JWT_REFRESH_SECRET, {\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;algorithms: &#91;\"HS256\"],\n\n&nbsp;&nbsp;&nbsp;&nbsp;});\n\n&nbsp;&nbsp;&nbsp;&nbsp;const user = await User.findById(payload.id);\n\n&nbsp;&nbsp;&nbsp;&nbsp;if (!user || !user.refreshTokens.includes(refreshToken)) {\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return res.status(403).json({ message: \"Refresh token revoked or reused\" });\n\n&nbsp;&nbsp;&nbsp;&nbsp;}\n\n&nbsp;&nbsp;&nbsp;&nbsp;\/\/ Rotation: remove the used token, issue a new pair\n\n&nbsp;&nbsp;&nbsp;&nbsp;const newRefreshToken = signRefreshToken(user.id);\n\n&nbsp;&nbsp;&nbsp;&nbsp;user.refreshTokens = user.refreshTokens.filter((t) =&gt; t !== refreshToken);\n\n&nbsp;&nbsp;&nbsp;&nbsp;user.refreshTokens.push(newRefreshToken);\n\n&nbsp;&nbsp;&nbsp;&nbsp;await user.save();\n\n&nbsp;&nbsp;&nbsp;&nbsp;res.json({ accessToken: signAccessToken(user.id), refreshToken: newRefreshToken });\n\n&nbsp;&nbsp;} catch (err) {\n\n&nbsp;&nbsp;&nbsp;&nbsp;res.status(401).json({ message: \"Invalid or expired refresh token\" });\n\n&nbsp;&nbsp;}\n\n});\n\nrouter.post(\"\/logout\", async (req, res) =&gt; {\n\n&nbsp;&nbsp;try {\n\n&nbsp;&nbsp;&nbsp;&nbsp;const { refreshToken } = req.body;\n\n&nbsp;&nbsp;&nbsp;&nbsp;const payload = jwt.verify(refreshToken, process.env.JWT_REFRESH_SECRET);\n\n&nbsp;&nbsp;&nbsp;&nbsp;await User.updateOne({ _id: payload.id }, { $pull: { refreshTokens: refreshToken } });\n\n&nbsp;&nbsp;} catch (err) {\n\n&nbsp;&nbsp;&nbsp;&nbsp;\/\/ An invalid token is already unusable, so logout still succeeds\n\n&nbsp;&nbsp;}\n\n&nbsp;&nbsp;res.json({ message: \"Logged out\" });\n\n});\n\nmodule.exports = router;<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Step 4: Create the authentication middleware and protect routes<\/strong><\/h3>\n\n\n\n<p>The middleware reads the Authorization header, checks the Bearer format, verifies the signature and expiry, and attaches the decoded payload to req.user. Any route that includes auth is now protected, like \/api\/profile in server.js.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ middleware\/auth.js\n\nconst jwt = require(\"jsonwebtoken\");\n\nmodule.exports = (req, res, next) =&gt; {\n\n&nbsp;&nbsp;const header = req.headers.authorization;\n\n&nbsp;&nbsp;if (!header || !header.startsWith(\"Bearer \")) {\n\n&nbsp;&nbsp;&nbsp;&nbsp;return res.status(401).json({ message: \"Missing or malformed Authorization header\" });\n\n&nbsp;&nbsp;}\n\n&nbsp;&nbsp;const token = header.split(\" \")&#91;1];\n\n&nbsp;&nbsp;try {\n\n&nbsp;&nbsp;&nbsp;&nbsp;req.user = jwt.verify(token, process.env.JWT_ACCESS_SECRET, { algorithms: &#91;\"HS256\"] });\n\n&nbsp;&nbsp;&nbsp;&nbsp;next();\n\n&nbsp;&nbsp;} catch (err) {\n\n&nbsp;&nbsp;&nbsp;&nbsp;const message = err.name === \"TokenExpiredError\" ? \"Token expired\" : \"Invalid token\";\n\n&nbsp;&nbsp;&nbsp;&nbsp;res.status(401).json({ message });\n\n&nbsp;&nbsp;}\n\n};\n\nStart the app with npx nodemon server.js.<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>JWT Access Token vs Refresh Token<\/strong><\/h2>\n\n\n\n<p>A JWT access token and refresh token solve different problems. The access token proves identity on each API call, so it must expire quickly in case it leaks. The refresh token lets the user stay signed in without typing a password again.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><\/td><td><strong>Access token<\/strong><\/td><td><strong>Refresh token<\/strong><\/td><\/tr><tr><td>Purpose<\/td><td>Authorizes API requests<\/td><td>Obtains new access tokens<\/td><\/tr><tr><td>Expiration<\/td><td>Short (for example, 15 minutes)<\/td><td>Longer (for example, 7 days)<\/td><\/tr><tr><td>Usage<\/td><td>Sent with every protected request<\/td><td>Sent only to the \/refresh and \/logout endpoints<\/td><\/tr><tr><td>Signing secret<\/td><td>JWT_ACCESS_SECRET<\/td><td>A separate JWT_REFRESH_SECRET<\/td><\/tr><tr><td>Security considerations<\/td><td>Stateless, so it cannot be revoked before expiry<\/td><td>Stored server-side so it can be revoked; a stolen one is high-risk<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>When the access token expires, the client sends the refresh token to \/api\/auth\/refresh and receives a new pair.<\/p>\n\n\n\n<p><strong>Rotation:<\/strong> every refresh issues a new refresh token and deletes the old one. If an old token is presented again, the server rejects it with a 403, which signals possible theft.<\/p>\n\n\n\n<p><strong>Revocation:<\/strong> because valid refresh tokens live in the user&#8217;s refreshTokens array, removing one (logout) or clearing the array (a security reset) invalidates it immediately.<\/p>\n\n\n\n<p><strong><em>Also Read: <a href=\"https:\/\/www.guvi.in\/blog\/cybersecurity-interview-questions-and-answers\/\" target=\"_blank\" rel=\"noreferrer noopener\">30 Sure Shot Cybersecurity Interview Questions and Answers<\/a><\/em><\/strong><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Test the JWT Authentication System Using Postman<\/strong><\/h2>\n\n\n\n<p>With the server running, set the body type to <strong>raw \u2192 JSON<\/strong> for each POST request.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>1. Register a user<\/strong><\/h3>\n\n\n\n<p>POST http:\/\/localhost:5000\/api\/auth\/register<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>{ \"name\": \"Asha\", \"email\": \"asha@example.com\", \"password\": \"Str0ngPass!\" }<\/code><\/pre>\n\n\n\n<p>Expected: 201 Created with the user&#8217;s id, name and email. The password is not returned.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>2. Log in and receive tokens<\/strong><\/h3>\n\n\n\n<p>POST http:\/\/localhost:5000\/api\/auth\/login with the email and password.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>{ \"accessToken\": \"eyJhbGciOi...\", \"refreshToken\": \"eyJhbGciOi...\" }<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>3. Access a protected endpoint<\/strong><\/h3>\n\n\n\n<p>GET http:\/\/localhost:5000\/api\/profile. Open the <strong>Authorization<\/strong> tab, choose <strong>Bearer Token<\/strong> and paste the access token.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>{ \"message\": \"Protected data\", \"userId\": \"6650f1c2...\" }<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>4. Test failure cases<\/strong><\/h3>\n\n\n\n<p>To test expiry quickly, temporarily set the access token&#8217;s expiresIn to &#8220;10s&#8221;, log in, wait, and call \/api\/profile again. Then call \/api\/auth\/refresh with your refresh token to get a new pair.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>JWT Authentication Security Best Practices<\/strong><\/h2>\n\n\n\n<p>A working login is not yet a secure one. Apply these measures before production:<\/p>\n\n\n\n<ul>\n<li><strong>Use strong secrets from the environment.<\/strong> Generate long random values, keep them out of source control, and use different secrets for access and refresh tokens.<\/li>\n\n\n\n<li><strong>Keep access tokens short-lived.<\/strong> Minutes, not days. A leaked token then stays useful for only a short time.<\/li>\n\n\n\n<li><strong>Use HTTPS everywhere.<\/strong> Tokens sent over plain HTTP can be intercepted.<\/li>\n\n\n\n<li><strong>Validate signatures and claims.<\/strong> Pin the allowed algorithm (algorithms: [&#8220;HS256&#8221;]), as the code above does, and check exp. Add issuer and audience checks if several services share tokens.<\/li>\n\n\n\n<li><strong>Keep the payload minimal.<\/strong> Store only an ID. Never include passwords or personal data, because the payload is readable by anyone.<\/li>\n\n\n\n<li><strong>Secure refresh-token storage.<\/strong> Store refresh tokens server-side so they can be revoked. In production, consider storing a hash of each token rather than the raw value.<\/li>\n\n\n\n<li><strong>Rotate and revoke refresh tokens.<\/strong> Rotate on every refresh, and clear a user&#8217;s tokens on password change or suspected compromise.<\/li>\n\n\n\n<li><strong>Rate-limit authentication endpoints.<\/strong> A package such as express-rate-limit on \/login and \/register slows brute-force attempts.<\/li>\n\n\n\n<li><strong>Prefer HttpOnly cookies in browsers.<\/strong> Sending the refresh token in a Secure, HttpOnly, SameSite cookie keeps it out of reach of JavaScript, which limits damage from XSS. If you use cookies, add CSRF protection.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Common JWT Authentication Errors<\/strong><\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>Error<\/strong><\/td><td><strong>Likely cause<\/strong><\/td><td><strong>Fix<\/strong><\/td><\/tr><tr><td>JsonWebTokenError: invalid token<\/td><td>Token is malformed, truncated or edited<\/td><td>Copy the full token again and check for stray quotes or spaces<\/td><\/tr><tr><td>TokenExpiredError: jwt expired<\/td><td>The exp time has passed<\/td><td>Call \/api\/auth\/refresh to get a new access token<\/td><\/tr><tr><td>Missing or malformed Authorization header<\/td><td>Header absent, or not in Bearer &lt;token&gt; form<\/td><td>Send Authorization: Bearer &lt;token&gt; with one space<\/td><\/tr><tr><td>JsonWebTokenError: invalid signature<\/td><td>Token was signed with a different secret<\/td><td>Check that .env values match and the server was restarted after changes<\/td><\/tr><tr><td>secret or public key must be provided<\/td><td>JWT_ACCESS_SECRET is undefined<\/td><td>Confirm dotenv loads before the routes and the variable name is spelled correctly<\/td><\/tr><tr><td>Refresh returns 403<\/td><td>Token was already rotated or revoked<\/td><td>Log in again to start a new session<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Conclusion<\/strong><\/h2>\n\n\n\n<p>JWT authentication lets a REST API verify callers without storing sessions. In this JWT authentication tutorial you built a complete login system: registration with bcrypt-hashed passwords, a login endpoint that issues access and refresh tokens, a refresh endpoint with rotation, logout with revocation, and middleware that protects routes.<\/p>\n\n\n\n<p>The code is a solid foundation, but production safety depends on how you handle tokens. Keep secrets in the environment, expire access tokens quickly, serve over HTTPS, rate-limit login attempts, and store refresh tokens carefully. Next, try adding role-based access control by putting a role claim in the access token and checking it in the middleware.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Frequently Asked Questions<\/strong><\/h2>\n\n\n<div id=\"rank-math-faq\" class=\"rank-math-block\">\n<div class=\"rank-math-list \">\n<div id=\"faq-question-1796212466197\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>1. What is JWT authentication in Node.js?<\/strong><\/h3>\n<div class=\"rank-math-answer \">\n\n<p>It is a method where an Express server signs a JSON Web Token with the jsonwebtoken library after a successful login. The client then sends that token on later requests, and middleware verifies it before allowing access.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1796212473032\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>2. How does JWT authentication work in REST APIs?<\/strong><\/h3>\n<div class=\"rank-math-answer \">\n\n<p>The client logs in, the server returns a signed token, and the client attaches it to each request in the Authorization header. The server checks the signature and expiry on every call, with no session lookup.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1796212492001\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>3. Is JWT more secure than session-based authentication?<\/strong><\/h3>\n<div class=\"rank-math-answer \">\n\n<p>Not inherently. Sessions can be revoked instantly because the server holds the state. JWTs scale easily without shared storage but cannot be revoked before expiry unless you add a revocation mechanism. Both are secure when implemented correctly.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1796212503605\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>4. What is the difference between an access token and a refresh token?<\/strong><\/h3>\n<div class=\"rank-math-answer \">\n\n<p>An access token is short-lived and authorizes API requests. A refresh token lasts longer and is used only to get new access tokens.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1796212513656\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>5. Where should JWT tokens be stored?<\/strong><\/h3>\n<div class=\"rank-math-answer \">\n\n<p>For browser apps, keep refresh tokens in Secure, HttpOnly cookies. Keep access tokens in memory where possible. Avoid localStorage for sensitive tokens, since any XSS flaw can read it. Mobile apps should use the platform&#8217;s secure storage.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1796212536450\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>6. Can JWT tokens be reused after expiration?<\/strong><\/h3>\n<div class=\"rank-math-answer \">\n\n<p>No. Once the exp time passes, verification fails and the server rejects the token. The client must use a valid refresh token to get a new access token.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1796212546079\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>7. How do you protect REST API routes using JWT?<\/strong><\/h3>\n<div class=\"rank-math-answer \">\n\n<p>Add authentication middleware that verifies the token, then place it before the route handler, as in app.get(&#8220;\/api\/profile&#8221;, auth, handler). Requests without a valid token get a 401 response.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1796212562240\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>8. Is JWT suitable for production applications?<\/strong><\/h3>\n<div class=\"rank-math-answer \">\n\n<p>Yes, when used with short expiries, HTTPS, strong secrets, refresh-token rotation and revocation. Many production APIs use it. For systems that need instant logout everywhere, pair it with server-side token tracking or consider sessions.<\/p>\n\n<\/div>\n<\/div>\n<\/div>\n<\/div>","protected":false},"excerpt":{"rendered":"<p>Every REST API that handles user data has to answer one question on each request: who is calling, and are they allowed in? HTTP is stateless, so the server does not remember a login between requests. Token-based authentication fixes this by handing the client a signed token at login and verifying it on every call [&hellip;]<\/p>\n","protected":false},"author":63,"featured_media":150486,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[294],"tags":[],"views":"16","authorinfo":{"name":"Vishalini Devarajan","url":"https:\/\/www.guvi.in\/blog\/author\/vishalini\/"},"thumbnailURL":"https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2026\/12\/jwt-authentication-tutorial-build-a-secure-login-system-in-nodejs-hd-300x116.webp","_links":{"self":[{"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/posts\/150478"}],"collection":[{"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/users\/63"}],"replies":[{"embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/comments?post=150478"}],"version-history":[{"count":9,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/posts\/150478\/revisions"}],"predecessor-version":[{"id":150588,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/posts\/150478\/revisions\/150588"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/media\/150486"}],"wp:attachment":[{"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/media?parent=150478"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/categories?post=150478"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/tags?post=150478"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}