

{"id":114707,"date":"2023-05-17T09:00:11","date_gmt":"2023-05-17T03:30:11","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=114707"},"modified":"2023-05-17T09:54:12","modified_gmt":"2023-05-17T04:24:12","slug":"jwt-in-express-js","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/jwt-in-express-js\/","title":{"rendered":"Express JS JWT"},"content":{"rendered":"<p>JSON Web Tokens (JWT) in Express JS is used for transmitting information between parties as a JSON object. It is used for authentication and authorization purposes in web apps. In this article, we will explore how to use JWT for authentication in an Express.js application.<\/p>\n<h3>Prerequisites to use Express JWT<\/h3>\n<p>Before diving into JWT authentication, you should have a basic understanding of Node.js, Express.js, and MongoDB. You should also have the following packages installed in your project:<\/p>\n<ul>\n<li>express<\/li>\n<li>mongoose<\/li>\n<li>bcrypt<\/li>\n<li>Jsonwebtoken<\/li>\n<\/ul>\n<h3>JSON Web Token JWT structure<\/h3>\n<p>A JWT consists of three parts: a header, a payload, and a signature.<\/p>\n<h4>1. Header:<\/h4>\n<p>The header of a JWT is a JSON object that describes the cryptographic operations used to generate the signature. It typically contains two fields:<\/p>\n<ul>\n<li><strong>&#8220;alg&#8221; (algorithm):<\/strong> The algorithm used to sign the token. Common values include HMAC SHA256 and RSA.<\/li>\n<li><strong>&#8220;typ&#8221; (type):<\/strong> The type of token, which is always &#8220;JWT&#8221;.<\/li>\n<\/ul>\n<p>The header is Base64Url-encoded to create the first part of the JWT.<\/p>\n<h4>2. Payload:<\/h4>\n<p>The payload of a JWT contains the claims, or statements, about an entity (typically, the user) and additional data. Claims can be of three types:<\/p>\n<p><strong>a. Registered claims:<\/strong> These are predefined claims that are recommended but not required to be used in a JWT. Examples include &#8220;iss&#8221; (issuer), &#8220;exp&#8221; (expiration time), and &#8220;sub&#8221; (subject).<\/p>\n<p><strong>b. Public claims:<\/strong> These are custom claims that are defined by the parties that use them. They should be defined in a namespace that avoids collisions with other names.<\/p>\n<p><strong>c. Private claims:<\/strong> These are custom claims that are defined by the parties that use them. They are not meant to be shared with other parties.<\/p>\n<p>The payload is also a JSON object, which is Base64Url-encoded to create the second part of the JWT.<\/p>\n<h4>3. Signature:<\/h4>\n<p>The signature of a JWT is used to verify that the sender of the JWT is who it says it is and to ensure that the message was not changed along the way. This is created by taking the encoded header, the encoded payload, a secret key, and the algorithm specified in the header and signing them. It is then added to the JWT as the third part.<\/p>\n<h3>Creating the Express Application<\/h3>\n<p>First, let&#8217;s create a new Express application using the following commands:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">mkdir express-jwt-auth\r\ncd express-jwt-auth\r\nnpm init -y\r\nnpm install express mongoose bcrypt jsonwebtoken\r\n<\/pre>\n<p>The above commands create a new directory called express-jwt-auth, initializes a new Node.js project with default values, and installs the required dependencies.<\/p>\n<p>Next, create a new file called app.js in the project root directory and add the following code:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">const express = require('express');\r\nconst mongoose = require('mongoose');\r\nconst bcrypt = require('bcrypt');\r\nconst jwt = require('jsonwebtoken');\r\nconst app = express();\r\nconst port = 3000;\r\n\r\napp.use(express.json());\r\n\r\nmongoose.connect('mongodb:\/\/localhost\/jwt-auth', {\r\n  useNewUrlParser: true,\r\n  useUnifiedTopology: true\r\n})\r\n.then(() =&gt; console.log('Connected to MongoDB'))\r\n.catch(err =&gt; console.log(err));\r\n\r\napp.listen(port, () =&gt; console.log(`Server running on port ${port}`));\r\n<\/pre>\n<p>In the above code, we require the required packages, initialize a new Express application, set the listening port to 3000, and connect to a MongoDB database named jwt-auth.<\/p>\n<h3>Creating a User Model<\/h3>\n<p>Next, let&#8217;s create a new user model that will be used for authentication. Create a new file called models\/User.js and add the following code:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">const mongoose = require('mongoose');\r\nconst bcrypt = require('bcrypt');\r\n\r\nconst userSchema = new mongoose.Schema({\r\n  username: {\r\n    type: String,\r\n    required: true,\r\n    unique: true\r\n  },\r\n  password: {\r\n    type: String,\r\n    required: true\r\n  }\r\n});\r\n\r\nuserSchema.pre('save', async function (next) {\r\n  const user = this;\r\n  if (user.isModified('password')) {\r\n    const salt = await bcrypt.genSalt();\r\n    user.password = await bcrypt.hash(user.password, salt);\r\n  }\r\n  next();\r\n});\r\n\r\nuserSchema.statics.authenticate = async function (username, password) {\r\n  const user = await this.findOne({ username });\r\n  if (!user) {\r\n    throw new Error('Invalid username');\r\n  }\r\n  const isMatch = await bcrypt.compare(password, user.password);\r\n  if (!isMatch) {\r\n    throw new Error('Invalid password');\r\n  }\r\n  return user;\r\n};\r\n\r\nconst User = mongoose.model('User', userSchema);\r\nmodule.exports = User;\r\n<\/pre>\n<p>In the above code, we define a new user schema with two fields &#8211; username and password. We also define a pre-save hook that hashes the password before saving it to the database. We also define a static method called authenticate that takes a username and password and returns the user if the credentials are valid, or throws an error otherwise.<\/p>\n<h3>Creating Authentication Routes<\/h3>\n<p>Next, let&#8217;s create the authentication routes that will handle user registration and login. In the app.js file, add the following code:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">const User = require('.\/models\/User');\r\n\r\napp.post('\/register', async (req, res) =&gt; {\r\n  const { username, password } = req.body;\r\n  try {\r\n    const user = new User({ username, password });\r\n    await user.save();\r\n    res.status(201).\r\nres.json({ message: 'User created successfully' });\r\n} catch (err) {\r\nres.status(400).json({ error: err.message });\r\n}\r\n});\r\n\r\napp.post('\/login', async (req, res) =&gt; {\r\nconst { username, password } = req.body;\r\ntry {\r\nconst user = await User.authenticate(username, password);\r\nconst token = jwt.sign({ userId: user._id }, 'secret');\r\nres.json({ token });\r\n} catch (err) {\r\nres.status(400).json({ error: err.message });\r\n}\r\n});\r\n<\/pre>\n<p>In the above code, we define two routes &#8211; `\/register` and `\/login`. The `register` route creates a new user and saves it to the database. The `login` route authenticates the user using the `authenticate` method of the user model and returns a JWT token if the authentication is successful.<\/p>\n<h3>Using the JWT Token for Authentication<\/h3>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/05\/session-based-authentication.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-114926\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/05\/session-based-authentication.webp\" alt=\"session based authentication\" width=\"800\" height=\"528\" \/><\/a><\/p>\n<p>Now that we have the JWT token, let&#8217;s use it to authenticate users. In the `app.js` file, add the following middleware:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">const requireAuth = (req, res, next) =&gt; {\r\n  const token = req.headers.authorization?.split(' ')[1];\r\n  if (token) {\r\n    jwt.verify(token, 'secret', (err, decodedToken) =&gt; {\r\n      if (err) {\r\n        res.status(401).json({ error: 'Unauthorized' });\r\n      } else {\r\n        req.userId = decodedToken.userId;\r\n        next();\r\n      }\r\n    });\r\n  } else {\r\n    res.status(401).json({ error: 'Unauthorized' });\r\n  }\r\n};\r\n\r\napp.get('\/profile', requireAuth, (req, res) =&gt; {\r\n  res.json({ userId: req.userId });\r\n});\r\n<\/pre>\n<p>In the above code, we define a middleware called requireAuth that checks for a JWT token in the Authorization header of the request. If the token is present, it verifies the token and sets the userId property of the request object. If the token is not present or invalid, it returns an error response. We also define a new route called \/profile that requires authentication and returns the userId of the authenticated user.<\/p>\n<h3>Conclusion<\/h3>\n<p>In this article, we have explored how to use JWT for authentication in an Express.js application. We have created a new user model, defined authentication routes, and used JWT tokens for authentication. We have also defined a middleware that checks for a JWT token and authenticates users.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>JSON Web Tokens (JWT) in Express JS is used for transmitting information between parties as a JSON object. It is used for authentication and authorization purposes in web apps. In this article, we will&#46;&#46;&#46;<\/p>\n","protected":false},"author":581,"featured_media":114798,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[27631],"tags":[27657,27658,27656],"class_list":["post-114707","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-express-js-tutorials","tag-express-js-jwt","tag-express-jwt","tag-jwt-in-express-js"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.8 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Express JS JWT - DataFlair<\/title>\n<meta name=\"description\" content=\"Learn to use JWT for authentication in Express js. Learn to create new user model, define authentication routes &amp; JWT tokens etc.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/data-flair.training\/blogs\/jwt-in-express-js\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Express JS JWT - DataFlair\" \/>\n<meta property=\"og:description\" content=\"Learn to use JWT for authentication in Express js. Learn to create new user model, define authentication routes &amp; JWT tokens etc.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/jwt-in-express-js\/\" \/>\n<meta property=\"og:site_name\" content=\"DataFlair\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/DataFlairWS\/\" \/>\n<meta property=\"article:published_time\" content=\"2023-05-17T03:30:11+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-05-17T04:24:12+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/04\/jwt-in-expressjs.webp\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/webp\" \/>\n<meta name=\"author\" content=\"DataFlair Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:site\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"DataFlair Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"5 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Express JS JWT - DataFlair","description":"Learn to use JWT for authentication in Express js. Learn to create new user model, define authentication routes & JWT tokens etc.","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:\/\/data-flair.training\/blogs\/jwt-in-express-js\/","og_locale":"en_US","og_type":"article","og_title":"Express JS JWT - DataFlair","og_description":"Learn to use JWT for authentication in Express js. Learn to create new user model, define authentication routes & JWT tokens etc.","og_url":"https:\/\/data-flair.training\/blogs\/jwt-in-express-js\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2023-05-17T03:30:11+00:00","article_modified_time":"2023-05-17T04:24:12+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/04\/jwt-in-expressjs.webp","type":"image\/webp"}],"author":"DataFlair Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"DataFlair Team","Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/jwt-in-express-js\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/jwt-in-express-js\/"},"author":{"name":"DataFlair Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/c187795dc82ab948373cca526df7c445"},"headline":"Express JS JWT","datePublished":"2023-05-17T03:30:11+00:00","dateModified":"2023-05-17T04:24:12+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/jwt-in-express-js\/"},"wordCount":769,"commentCount":1,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/jwt-in-express-js\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/04\/jwt-in-expressjs.webp","keywords":["Express JS JWT","Express JWT","JWT in Express JS"],"articleSection":["Express JS Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/jwt-in-express-js\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/jwt-in-express-js\/","url":"https:\/\/data-flair.training\/blogs\/jwt-in-express-js\/","name":"Express JS JWT - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/jwt-in-express-js\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/jwt-in-express-js\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/04\/jwt-in-expressjs.webp","datePublished":"2023-05-17T03:30:11+00:00","dateModified":"2023-05-17T04:24:12+00:00","description":"Learn to use JWT for authentication in Express js. Learn to create new user model, define authentication routes & JWT tokens etc.","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/jwt-in-express-js\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/jwt-in-express-js\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/jwt-in-express-js\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/04\/jwt-in-expressjs.webp","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/04\/jwt-in-expressjs.webp","width":1200,"height":628,"caption":"jwt in expressjs"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/jwt-in-express-js\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog Home","item":"https:\/\/data-flair.training\/blogs\/"},{"@type":"ListItem","position":2,"name":"Express JS Tutorials","item":"https:\/\/data-flair.training\/blogs\/category\/express-js-tutorials\/"},{"@type":"ListItem","position":3,"name":"Express JS JWT"}]},{"@type":"WebSite","@id":"https:\/\/data-flair.training\/blogs\/#website","url":"https:\/\/data-flair.training\/blogs\/","name":"DataFlair","description":"Learn Today. Lead Tomorrow.","publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/data-flair.training\/blogs\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/data-flair.training\/blogs\/#organization","name":"DataFlair","url":"https:\/\/data-flair.training\/blogs\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","width":106,"height":48,"caption":"DataFlair"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/DataFlairWS\/","https:\/\/x.com\/DataFlairWS","https:\/\/www.linkedin.com\/company\/dataflair-web-services-pvt-ltd\/","https:\/\/www.youtube.com\/user\/DataFlairWS"]},{"@type":"Person","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/c187795dc82ab948373cca526df7c445","name":"DataFlair Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","caption":"DataFlair Team"},"description":"DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.","url":"https:\/\/data-flair.training\/blogs\/author\/dfteam6\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/114707","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/users\/581"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=114707"}],"version-history":[{"count":5,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/114707\/revisions"}],"predecessor-version":[{"id":114927,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/114707\/revisions\/114927"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/114798"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=114707"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=114707"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=114707"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}