{"id":8516,"date":"2025-12-15T06:12:03","date_gmt":"2025-12-15T06:12:03","guid":{"rendered":"https:\/\/studysection.com\/blog\/?p=8516"},"modified":"2025-12-15T06:12:03","modified_gmt":"2025-12-15T06:12:03","slug":"jwt-authentication-in-express-js","status":"publish","type":"post","link":"https:\/\/studysection.com\/blog\/jwt-authentication-in-express-js\/","title":{"rendered":"JWT Authentication in Express.js"},"content":{"rendered":"<p>Authentication is a critical part of nearly every web application. One of the most popular methods today is using JWT (JSON Web Tokens) \u2014 a compact, secure way to verify user identity without storing session data on the server.<br \/>\nWe&#8217;ll walk through how to implement JWT-based authentication in a <a href=\"https:\/\/blog.webnersolutions.com\/caching-in-node-js-with-redis-a-beginners-guide\/\">Node.js<\/a> + <a href=\"https:\/\/studysection.com\/blog\/what-is-express-js-explain-the-example\/\">Express.js<\/a> app.<\/p>\n<p><strong>Step 1: Set Up Your Express Project<\/strong><br \/>\nFirst, create Node.js project using the below commands:<\/p>\n<pre><code>mkdir jwt-auth-demo &amp;&amp; cd jwt-auth-demo\r\nnpm init -y\r\nnpm install express jsonwebtoken dotenv<\/code><\/pre>\n<p>You may also want to install nodemon for automatic server reloads during development.<\/p>\n<p><strong>Step 2: Create Basic Server Structure<\/strong><br \/>\nCreate a file named index.js file and also create a basic server:<\/p>\n<pre><code>  \/\/ index.js\r\n  import express from 'express';\r\n  import dotenv from 'dotenv';\r\n\r\n  dotenv.config();\r\n  const app = express();\r\n  app.use(express.json());\r\n\r\n  const PORT = process.env.PORT || 3000;\r\n  app.listen(PORT, () =&gt; console.log(`Server running on port ${PORT}`));<\/code><\/pre>\n<p>Make sure to create a .env file:<\/p>\n<pre><code>PORT=3000\r\nJWT_SECRET=mySuperSecretKey<\/code><\/pre>\n<p><strong>Step 3: Generate JWT on Login<\/strong><br \/>\nLet\u2019s assume a basic login system. You\u2019ll typically verify user credentials from a database. For simplicity, we\u2019ll hard-code a dummy user.<\/p>\n<pre><code>\/\/ authController.js\r\n\r\n import jwt from 'jsonwebtoken';\r\n\r\n export const login = (req, res) =&gt; {\r\n    const { email, password } = req.body;\r\n    \/\/ Mock user check \u2014 in real apps, validate against DB\r\n    if (email === 'test@example.com' &amp;&amp; password === 'password123') {\r\n        const token = jwt.sign(\r\n            { userId: '12345', email },\r\n            process.env.JWT_SECRET,\r\n            { expiresIn: '1h' }\r\n        );\r\n\r\n        return res.json({ success: true, token });\r\n    } else {\r\n        return res.status(401).json({ success: false, message:   'Invalid credentials' });\r\n    }\r\n };<\/code><\/pre>\n<p>Now set up a route for login:<\/p>\n<pre><code>\/\/ routes.js\r\n    import express from 'express';\r\n    import { login } from '.\/authController.js';\r\n   \r\n    const router = express.Router();\r\n   \r\n    router.post('\/login', login);\r\n   \r\n    export default router;\r\n   \r\n    Update index.js to use the route:\r\n    import routes from '.\/routes.js';\r\n    app.use('\/api', routes);<\/code><\/pre>\n<p><strong>Step 4: Create JWT Middleware to Protect Routes<\/strong><br \/>\nThis middleware will verify the token and attach user info to the request:<\/p>\n<pre><code>\/\/ middleware\/userAuth.js\r\n    import jwt from 'jsonwebtoken';\r\n   \r\n    const userAuth = (req, res, next) =&gt; {\r\n        const authHeader = req.headers.authorization;\r\n   \r\n        if (!authHeader || !authHeader.startsWith('Bearer ')) {\r\n            return res.status(401).json({ success: false, message: 'Unauthorized' });\r\n        }\r\n   \r\n        const token = authHeader.split(' ')[1];\r\n   \r\n        try {\r\n            const decoded = jwt.verify(token, process.env.JWT_SECRET);\r\n            req.user = decoded;\r\n            next();\r\n        } catch (err) {\r\n            return res.status(403).json({ success: false, message: 'Invalid or expired token' });\r\n        }\r\n    };\r\n   \r\n    export default userAuth;<\/code><\/pre>\n<p><strong>Step 5: Protect Routes Using the Middleware<\/strong><br \/>\nAdd a protected route that only logged-in users can access:<\/p>\n<pre><code> \/\/ routes.js\r\n    import userAuth from '.\/middleware\/userAuth.js';\r\n   \r\n    router.post('\/testing', userAuth, (req, res) =&gt; {\r\n        res.json({ success: true, message: `This is a testing Route.` });\r\n    });<\/code><\/pre>\n<p><strong>Step 6: Test the API<\/strong><\/p>\n<ol>\n<li>Login by sending a POST request to \/api\/login with valid credentials:<\/li>\n<\/ol>\n<pre><code>{\r\n    \"email\": \"test@example.com\",\r\n    \"password\": \"password123\"\r\n    }<\/code><\/pre>\n<ol start=\"2\">\n<li>Copy the returned token.<\/li>\n<li>Access protected route \/api\/testing by adding the token in the request header:<\/li>\n<\/ol>\n<p>Authorization: Bearer<br \/>\nIf the token is valid, you\u2019ll get a valid response.<\/p>\n<p><strong>Summary<\/strong><br \/>\nJWT authentication in Express.js is a powerful and scalable way to protect your APIs. By storing user information securely in the token and verifying it on each request, you eliminate the need for traditional server-side session handling.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Authentication is a critical part of nearly every web application. One of the most popular methods today is using JWT<\/p>\n","protected":false},"author":1,"featured_media":8517,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[6],"tags":[],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v21.7 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>JWT Authentication in Express.js<\/title>\n<meta name=\"description\" content=\"JWT authentication in Express.js is a powerful and scalable way to protect your APIs. Walk through how to implement JWT-based authentication in a Node.js + Express.js app.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/studysection.com\/blog\/jwt-authentication-in-express-js\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"JWT Authentication in Express.js\" \/>\n<meta property=\"og:description\" content=\"JWT authentication in Express.js is a powerful and scalable way to protect your APIs. Walk through how to implement JWT-based authentication in a Node.js + Express.js app.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/studysection.com\/blog\/jwt-authentication-in-express-js\/\" \/>\n<meta property=\"og:site_name\" content=\"Blog Posts on famous people, innovations and educational topics\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/studysection\" \/>\n<meta property=\"article:published_time\" content=\"2025-12-15T06:12:03+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2025\/12\/JWT-Authentication-in-Express.js-.png\" \/>\n\t<meta property=\"og:image:width\" content=\"940\" \/>\n\t<meta property=\"og:image:height\" content=\"788\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"admin-studysection-blog\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@studysection\" \/>\n<meta name=\"twitter:site\" content=\"@studysection\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"admin-studysection-blog\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"2 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/studysection.com\/blog\/jwt-authentication-in-express-js\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/studysection.com\/blog\/jwt-authentication-in-express-js\/\"},\"author\":{\"name\":\"admin-studysection-blog\",\"@id\":\"https:\/\/studysection.com\/blog\/#\/schema\/person\/db367e2c29a12d1808fb1979edb3d402\"},\"headline\":\"JWT Authentication in Express.js\",\"datePublished\":\"2025-12-15T06:12:03+00:00\",\"dateModified\":\"2025-12-15T06:12:03+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/studysection.com\/blog\/jwt-authentication-in-express-js\/\"},\"wordCount\":268,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/studysection.com\/blog\/#organization\"},\"articleSection\":[\"Learn and Grow\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/studysection.com\/blog\/jwt-authentication-in-express-js\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/studysection.com\/blog\/jwt-authentication-in-express-js\/\",\"url\":\"https:\/\/studysection.com\/blog\/jwt-authentication-in-express-js\/\",\"name\":\"JWT Authentication in Express.js\",\"isPartOf\":{\"@id\":\"https:\/\/studysection.com\/blog\/#website\"},\"datePublished\":\"2025-12-15T06:12:03+00:00\",\"dateModified\":\"2025-12-15T06:12:03+00:00\",\"description\":\"JWT authentication in Express.js is a powerful and scalable way to protect your APIs. Walk through how to implement JWT-based authentication in a Node.js + Express.js app.\",\"breadcrumb\":{\"@id\":\"https:\/\/studysection.com\/blog\/jwt-authentication-in-express-js\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/studysection.com\/blog\/jwt-authentication-in-express-js\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/studysection.com\/blog\/jwt-authentication-in-express-js\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/studysection.com\/blog\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"JWT Authentication in Express.js\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/studysection.com\/blog\/#website\",\"url\":\"https:\/\/studysection.com\/blog\/\",\"name\":\"Blog Posts on famous people, innovations and educational topics\",\"description\":\"\",\"publisher\":{\"@id\":\"https:\/\/studysection.com\/blog\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/studysection.com\/blog\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/studysection.com\/blog\/#organization\",\"name\":\"StudySection\",\"url\":\"https:\/\/studysection.com\/blog\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/studysection.com\/blog\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2021\/10\/studySection-logo.png\",\"contentUrl\":\"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2021\/10\/studySection-logo.png\",\"width\":920,\"height\":440,\"caption\":\"StudySection\"},\"image\":{\"@id\":\"https:\/\/studysection.com\/blog\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/studysection\",\"https:\/\/twitter.com\/studysection\",\"https:\/\/www.instagram.com\/study.section\/\",\"https:\/\/www.linkedin.com\/company\/studysection\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/studysection.com\/blog\/#\/schema\/person\/db367e2c29a12d1808fb1979edb3d402\",\"name\":\"admin-studysection-blog\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/studysection.com\/blog\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/054ac87a6874df1932004239cd8eab36?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/054ac87a6874df1932004239cd8eab36?s=96&d=mm&r=g\",\"caption\":\"admin-studysection-blog\"},\"url\":\"https:\/\/studysection.com\/blog\/author\/admin-studysection-blog\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"JWT Authentication in Express.js","description":"JWT authentication in Express.js is a powerful and scalable way to protect your APIs. Walk through how to implement JWT-based authentication in a Node.js + Express.js app.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/studysection.com\/blog\/jwt-authentication-in-express-js\/","og_locale":"en_US","og_type":"article","og_title":"JWT Authentication in Express.js","og_description":"JWT authentication in Express.js is a powerful and scalable way to protect your APIs. Walk through how to implement JWT-based authentication in a Node.js + Express.js app.","og_url":"https:\/\/studysection.com\/blog\/jwt-authentication-in-express-js\/","og_site_name":"Blog Posts on famous people, innovations and educational topics","article_publisher":"https:\/\/www.facebook.com\/studysection","article_published_time":"2025-12-15T06:12:03+00:00","og_image":[{"width":940,"height":788,"url":"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2025\/12\/JWT-Authentication-in-Express.js-.png","type":"image\/png"}],"author":"admin-studysection-blog","twitter_card":"summary_large_image","twitter_creator":"@studysection","twitter_site":"@studysection","twitter_misc":{"Written by":"admin-studysection-blog","Est. reading time":"2 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/studysection.com\/blog\/jwt-authentication-in-express-js\/#article","isPartOf":{"@id":"https:\/\/studysection.com\/blog\/jwt-authentication-in-express-js\/"},"author":{"name":"admin-studysection-blog","@id":"https:\/\/studysection.com\/blog\/#\/schema\/person\/db367e2c29a12d1808fb1979edb3d402"},"headline":"JWT Authentication in Express.js","datePublished":"2025-12-15T06:12:03+00:00","dateModified":"2025-12-15T06:12:03+00:00","mainEntityOfPage":{"@id":"https:\/\/studysection.com\/blog\/jwt-authentication-in-express-js\/"},"wordCount":268,"commentCount":0,"publisher":{"@id":"https:\/\/studysection.com\/blog\/#organization"},"articleSection":["Learn and Grow"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/studysection.com\/blog\/jwt-authentication-in-express-js\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/studysection.com\/blog\/jwt-authentication-in-express-js\/","url":"https:\/\/studysection.com\/blog\/jwt-authentication-in-express-js\/","name":"JWT Authentication in Express.js","isPartOf":{"@id":"https:\/\/studysection.com\/blog\/#website"},"datePublished":"2025-12-15T06:12:03+00:00","dateModified":"2025-12-15T06:12:03+00:00","description":"JWT authentication in Express.js is a powerful and scalable way to protect your APIs. Walk through how to implement JWT-based authentication in a Node.js + Express.js app.","breadcrumb":{"@id":"https:\/\/studysection.com\/blog\/jwt-authentication-in-express-js\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/studysection.com\/blog\/jwt-authentication-in-express-js\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/studysection.com\/blog\/jwt-authentication-in-express-js\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/studysection.com\/blog\/"},{"@type":"ListItem","position":2,"name":"JWT Authentication in Express.js"}]},{"@type":"WebSite","@id":"https:\/\/studysection.com\/blog\/#website","url":"https:\/\/studysection.com\/blog\/","name":"Blog Posts on famous people, innovations and educational topics","description":"","publisher":{"@id":"https:\/\/studysection.com\/blog\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/studysection.com\/blog\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/studysection.com\/blog\/#organization","name":"StudySection","url":"https:\/\/studysection.com\/blog\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/studysection.com\/blog\/#\/schema\/logo\/image\/","url":"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2021\/10\/studySection-logo.png","contentUrl":"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2021\/10\/studySection-logo.png","width":920,"height":440,"caption":"StudySection"},"image":{"@id":"https:\/\/studysection.com\/blog\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/studysection","https:\/\/twitter.com\/studysection","https:\/\/www.instagram.com\/study.section\/","https:\/\/www.linkedin.com\/company\/studysection"]},{"@type":"Person","@id":"https:\/\/studysection.com\/blog\/#\/schema\/person\/db367e2c29a12d1808fb1979edb3d402","name":"admin-studysection-blog","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/studysection.com\/blog\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/054ac87a6874df1932004239cd8eab36?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/054ac87a6874df1932004239cd8eab36?s=96&d=mm&r=g","caption":"admin-studysection-blog"},"url":"https:\/\/studysection.com\/blog\/author\/admin-studysection-blog\/"}]}},"views":138,"_links":{"self":[{"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/posts\/8516"}],"collection":[{"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/comments?post=8516"}],"version-history":[{"count":1,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/posts\/8516\/revisions"}],"predecessor-version":[{"id":8518,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/posts\/8516\/revisions\/8518"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/media\/8517"}],"wp:attachment":[{"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/media?parent=8516"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/categories?post=8516"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/tags?post=8516"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}