{
    "componentChunkName": "component---src-pages-blog-markdown-remark-fields-slug-js",
    "path": "/blog/user-authentication-in-node",
    "result": {"data":{"markdownRemark":{"html":"<h1 id=\"table-of-contents\" style=\"position:relative;\"><a href=\"#table-of-contents\" aria-label=\"table of contents permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Table of Contents</h1>\n<ul>\n<li><a href=\"#introduction\">Introduction</a></li>\n<li><a href=\"#handling-authorization-in-nodejs\">Handling Authorization in Node.js</a></li>\n<li><a href=\"#nodejs-user-authentication-prerequisites\">Node.js User Authentication Prerequisites</a></li>\n<li><a href=\"#how-to-implement-user-authentication-in-nodejs\">How to Implement User Authentication in Node.js</a>\n<ul>\n<li><a href=\"#backend-implementation\">Backend Implementation</a>\n<ul>\n<li><a href=\"#step-1-user-registration-process\">Step 1: User Registration Process</a></li>\n<li><a href=\"#step-2-login-and-session-management\">Step 2: Login and Session Management</a></li>\n<li><a href=\"#step-3-protecting-routes-with-middleware\">Step 3: Protecting Routes with Middleware</a></li>\n</ul>\n</li>\n<li><a href=\"#frontend-implementation\">Frontend Implementation</a></li>\n</ul>\n</li>\n<li><a href=\"#common-pitfalls-and-security-best-practices\">Common Pitfalls and Security Best Practices</a></li>\n<li><a href=\"#simplify-authentication-with-supertokens\">Simplify Authentication with Supertokens</a></li>\n<li><a href=\"#conclusion\">Conclusion</a></li>\n</ul>\n<h1 id=\"introduction\" style=\"position:relative;\"><a href=\"#introduction\" aria-label=\"introduction permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Introduction</strong></h1>\n<p>Authentication and authorization are essential for web applications to ensure that only legitimate users gain access and that they can perform actions based on their permissions. <strong>Node.js</strong> and <strong>Express.js</strong> are popular tools for building these systems because they allow developers to create fast, scalable apps efficiently.</p>\n<p>However, implementing authentication can be challenging—<strong>securing passwords, managing sessions</strong>, and ensuring tokens aren’t misused require careful planning. Authorization adds more complexity by defining user roles and permissions, ensuring users only access what they’re allowed to. Good user management is critical for protecting both <strong>user data</strong> and <strong>application security</strong>, while also maintaining a smooth user experience.</p>\n<h1 id=\"handling-authorization-in-nodejs\" style=\"position:relative;\"><a href=\"#handling-authorization-in-nodejs\" aria-label=\"handling authorization in nodejs permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Handling Authorization in Node.js</strong></h1>\n<h4 id=\"difference-between-authentication-and-authorization\" style=\"position:relative;\"><a href=\"#difference-between-authentication-and-authorization\" aria-label=\"difference between authentication and authorization permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Difference Between Authentication and Authorization</strong></h4>\n<ul>\n<li><strong>Authentication:</strong>\nThis process confirms the <strong>identity of the user</strong>—essentially verifying who they are. It typically involves methods like <strong>username and password checks</strong>, <strong>social login</strong>, or <strong>multi-factor authentication</strong> (MFA). For example, when a user logs into an application, authentication ensures that the individual is who they claim to be.</li>\n<li><strong>Authorization:</strong>\nAuthorization determines <strong>what actions or resources the authenticated user can access</strong>. Once a user is authenticated, authorization checks whether they have the necessary permissions to perform specific operations, such as editing content or accessing admin features.</li>\n</ul>\n<p>Authentication and authorization complement each other: authentication verifies the user, while authorization governs the <strong>extent of their access</strong> within the system.</p>\n<hr>\n<h4 id=\"implementing-role-based-access-control-rbac\" style=\"position:relative;\"><a href=\"#implementing-role-based-access-control-rbac\" aria-label=\"implementing role based access control rbac permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Implementing Role-Based Access Control (RBAC)</strong></h4>\n<p>RBAC is a widely used strategy to <strong>manage user permissions efficiently</strong> by assigning roles to users. It simplifies authorization by grouping permissions under specific roles.</p>\n<ul>\n<li><strong>Assigning roles to users:</strong>\nUsers are given predefined roles such as <strong>admin, editor, or viewer</strong>. Each role corresponds to a set of permissions. For example:\n<ul>\n<li><strong>Admin</strong>: Full access to all operations, including creating, editing, and deleting content.</li>\n<li><strong>Editor</strong>: Can modify content but lacks access to administrative settings.</li>\n<li><strong>Viewer</strong>: Read-only access to content.</li>\n</ul>\n</li>\n<li><strong>Defining permissions for each role:</strong>\nEach role has specific permissions that determine <strong>what resources the user can access</strong> and <strong>what actions they can perform</strong>. For example:\n<ul>\n<li>Admins can manage other users and change system configurations.</li>\n<li>Editors can update or delete content but cannot manage users.</li>\n</ul>\n</li>\n<li><strong>Importance of clear access rules:</strong>\n<ul>\n<li>Well-defined access rules <strong>reduce the risk of security loopholes</strong>. For example, without proper role separation, unauthorized users could gain access to sensitive data or critical system operations.</li>\n<li><strong>Consistency</strong> in applying roles and permissions ensures better maintainability. Centralized control via middleware helps avoid inconsistencies, preventing scenarios where users have unintended privileges.</li>\n</ul>\n</li>\n</ul>\n<p>RBAC simplifies managing access, especially in applications with many users. By grouping permissions under roles, developers can ensure that <strong>user privileges are clear and manageable</strong>, helping to maintain a secure system.</p>\n<h1 id=\"nodejs-user-authentication-prerequisites\" style=\"position:relative;\"><a href=\"#nodejs-user-authentication-prerequisites\" aria-label=\"nodejs user authentication prerequisites permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Node.js User Authentication Prerequisites</strong></h1>\n<p>To set up a secure user <a href=\"https://supertokens.com/blog/how-to-deploy-supertokens-with-react-nodejs-express-on-vercel\" target=\"_blank\" rel=\"nofollow\">authentication system in Node.js</a>, you’ll need several essential tools and packages. These will enable you to handle routing, password encryption, token management, and cookie parsing, laying the groundwork for a robust authentication flow.</p>\n<h4 id=\"setting-up-the-environment\" style=\"position:relative;\"><a href=\"#setting-up-the-environment\" aria-label=\"setting up the environment permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Setting Up the Environment</strong></h4>\n<p>Install the following packages</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"61893359420202160000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`npm init -y\nnpm install express bcrypt jsonwebtoken cookie-parser`, `61893359420202160000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"bash\"><pre class=\"language-bash\"><code class=\"language-bash\"><span class=\"token function\">npm</span> init -y\n<span class=\"token function\">npm</span> <span class=\"token function\">install</span> express bcrypt jsonwebtoken cookie-parser</code></pre></div>\n<p>Run the server with the following command</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"65734110135990800000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`node server.js`, `65734110135990800000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"bash\"><pre class=\"language-bash\"><code class=\"language-bash\"><span class=\"token function\">node</span> server.js</code></pre></div>\n<hr>\n<h4 id=\"choosing-an-authentication-method\" style=\"position:relative;\"><a href=\"#choosing-an-authentication-method\" aria-label=\"choosing an authentication method permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Choosing an Authentication Method</strong></h4>\n<p>There are several popular methods for handling authentication in web applications. Here’s an overview of the most commonly used approaches:</p>\n<ul>\n<li><strong>JWT (JSON Web Tokens)</strong>: JWTs are used for <strong>stateless authentication</strong>, meaning the server doesn’t store session information. Instead, a token is generated when the user logs in, which includes encoded user data and is sent with each request. The server then verifies the token to authenticate the user, making JWTs ideal for scalable, stateless applications.</li>\n<li><strong>Session-based Authentication</strong>: This method involves storing session data on the server to keep track of user activity. When a user logs in, a session is created on the server, and a unique session ID is sent to the user’s browser, often in a cookie. This session ID is then used to identify the user for future requests. Session-based authentication is commonly used in applications where maintaining user state is essential.</li>\n<li><strong>OAuth</strong>: OAuth is often used for third-party login, allowing users to sign in with existing accounts from services like Google, Facebook, or GitHub. It simplifies user login by leveraging these providers for authentication, eliminating the need for users to create new credentials for each application. OAuth is widely used in applications that prioritize user convenience and wish to offer social login options.</li>\n</ul>\n<h4 id=\"setting-up-the-server-and-authentication-routes\" style=\"position:relative;\"><a href=\"#setting-up-the-server-and-authentication-routes\" aria-label=\"setting up the server and authentication routes permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Setting Up the Server and Authentication Routes</strong></h4>\n<p>To configure the server, connect to MongoDB, and set up authentication routes, write the following code in the <code class=\"language-text\">Index.js</code> file:</p>\n<h3 id=\"indexjs\" style=\"position:relative;\"><a href=\"#indexjs\" aria-label=\"indexjs permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Index.js</strong></h3>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"87731991274266100000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`const express = require('express');\nconst mongoose = require('mongoose');\nconst cors = require('cors');\nconst dotenv = require('dotenv');\nconst Message = require('./models/Message');\nconst authRoutes = require('./routes/auth');\nconst auth = require('./middleware/auth');\n\ndotenv.config();\nconst app = express();\nconst PORT = process.env.PORT || 5000;\n\napp.use(cors());\napp.use(express.json());\n\n\n\n// Routes\napp.use('/api/auth', authRoutes);\n\n// Protected route (only accessible with a valid token)\napp.get('/api/private', auth, (req, res) => {\n     res.send('This is a protected route');\n   });\n\n\n\napp.get('/', (req, res) => {\n     res.send('Hello World!');\n});\n\napp.post('/message', async (req, res) => {\n     const newMessage = new Message({ text: req.body.text });\n     try{\n         await newMessage.save();\n         res.status(201).json(newMessage);\n     } catch (error) {\n         res.status(500).json({ error: 'Error saving message' });\n     }\n})\n\n\nmongoose\n     .connect(process.env.MONGO\\_URI)\n     .then(() => console.log('MongoDB Connected'))\n     .catch((err) => console.log('MongoDB connection error:', err));\n\napp.listen(PORT, () => {\n     console.log(\\`Server is running on port \\${PORT}\\`);\n});`, `87731991274266100000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"typescript\"><pre class=\"language-typescript\"><code class=\"language-typescript\"><span class=\"token keyword\">const</span> express <span class=\"token operator\">=</span> <span class=\"token keyword\">require</span><span class=\"token punctuation\">(</span><span class=\"token string\">'express'</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">const</span> mongoose <span class=\"token operator\">=</span> <span class=\"token keyword\">require</span><span class=\"token punctuation\">(</span><span class=\"token string\">'mongoose'</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">const</span> cors <span class=\"token operator\">=</span> <span class=\"token keyword\">require</span><span class=\"token punctuation\">(</span><span class=\"token string\">'cors'</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">const</span> dotenv <span class=\"token operator\">=</span> <span class=\"token keyword\">require</span><span class=\"token punctuation\">(</span><span class=\"token string\">'dotenv'</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">const</span> Message <span class=\"token operator\">=</span> <span class=\"token keyword\">require</span><span class=\"token punctuation\">(</span><span class=\"token string\">'./models/Message'</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">const</span> authRoutes <span class=\"token operator\">=</span> <span class=\"token keyword\">require</span><span class=\"token punctuation\">(</span><span class=\"token string\">'./routes/auth'</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">const</span> auth <span class=\"token operator\">=</span> <span class=\"token keyword\">require</span><span class=\"token punctuation\">(</span><span class=\"token string\">'./middleware/auth'</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\ndotenv<span class=\"token punctuation\">.</span><span class=\"token function\">config</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">const</span> app <span class=\"token operator\">=</span> <span class=\"token function\">express</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">const</span> <span class=\"token constant\">PORT</span> <span class=\"token operator\">=</span> process<span class=\"token punctuation\">.</span>env<span class=\"token punctuation\">.</span><span class=\"token constant\">PORT</span> <span class=\"token operator\">||</span> <span class=\"token number\">5000</span><span class=\"token punctuation\">;</span>\n\napp<span class=\"token punctuation\">.</span><span class=\"token function\">use</span><span class=\"token punctuation\">(</span><span class=\"token function\">cors</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\napp<span class=\"token punctuation\">.</span><span class=\"token function\">use</span><span class=\"token punctuation\">(</span>express<span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n\n\n<span class=\"token comment\">// Routes</span>\napp<span class=\"token punctuation\">.</span><span class=\"token function\">use</span><span class=\"token punctuation\">(</span><span class=\"token string\">'/api/auth'</span><span class=\"token punctuation\">,</span> authRoutes<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n<span class=\"token comment\">// Protected route (only accessible with a valid token)</span>\napp<span class=\"token punctuation\">.</span><span class=\"token function\">get</span><span class=\"token punctuation\">(</span><span class=\"token string\">'/api/private'</span><span class=\"token punctuation\">,</span> auth<span class=\"token punctuation\">,</span> <span class=\"token punctuation\">(</span>req<span class=\"token punctuation\">,</span> res<span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n     res<span class=\"token punctuation\">.</span><span class=\"token function\">send</span><span class=\"token punctuation\">(</span><span class=\"token string\">'This is a protected route'</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n\n\napp<span class=\"token punctuation\">.</span><span class=\"token function\">get</span><span class=\"token punctuation\">(</span><span class=\"token string\">'/'</span><span class=\"token punctuation\">,</span> <span class=\"token punctuation\">(</span>req<span class=\"token punctuation\">,</span> res<span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n     res<span class=\"token punctuation\">.</span><span class=\"token function\">send</span><span class=\"token punctuation\">(</span><span class=\"token string\">'Hello World!'</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\napp<span class=\"token punctuation\">.</span><span class=\"token function\">post</span><span class=\"token punctuation\">(</span><span class=\"token string\">'/message'</span><span class=\"token punctuation\">,</span> <span class=\"token keyword\">async</span> <span class=\"token punctuation\">(</span>req<span class=\"token punctuation\">,</span> res<span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n     <span class=\"token keyword\">const</span> newMessage <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Message</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> text<span class=\"token operator\">:</span> req<span class=\"token punctuation\">.</span>body<span class=\"token punctuation\">.</span>text <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n     <span class=\"token keyword\">try</span><span class=\"token punctuation\">{</span>\n         <span class=\"token keyword\">await</span> newMessage<span class=\"token punctuation\">.</span><span class=\"token function\">save</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n         res<span class=\"token punctuation\">.</span><span class=\"token function\">status</span><span class=\"token punctuation\">(</span><span class=\"token number\">201</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span>newMessage<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n     <span class=\"token punctuation\">}</span> <span class=\"token keyword\">catch</span> <span class=\"token punctuation\">(</span>error<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n         res<span class=\"token punctuation\">.</span><span class=\"token function\">status</span><span class=\"token punctuation\">(</span><span class=\"token number\">500</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> error<span class=\"token operator\">:</span> <span class=\"token string\">'Error saving message'</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n     <span class=\"token punctuation\">}</span>\n<span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n\n\nmongoose\n     <span class=\"token punctuation\">.</span><span class=\"token function\">connect</span><span class=\"token punctuation\">(</span>process<span class=\"token punctuation\">.</span>env<span class=\"token punctuation\">.</span><span class=\"token constant\">MONGO</span>\\_URI<span class=\"token punctuation\">)</span>\n     <span class=\"token punctuation\">.</span><span class=\"token function\">then</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token builtin\">console</span><span class=\"token punctuation\">.</span><span class=\"token function\">log</span><span class=\"token punctuation\">(</span><span class=\"token string\">'MongoDB Connected'</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span>\n     <span class=\"token punctuation\">.</span><span class=\"token function\">catch</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span>err<span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token builtin\">console</span><span class=\"token punctuation\">.</span><span class=\"token function\">log</span><span class=\"token punctuation\">(</span><span class=\"token string\">'MongoDB connection error:'</span><span class=\"token punctuation\">,</span> err<span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\napp<span class=\"token punctuation\">.</span><span class=\"token function\">listen</span><span class=\"token punctuation\">(</span><span class=\"token constant\">PORT</span><span class=\"token punctuation\">,</span> <span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n     <span class=\"token builtin\">console</span><span class=\"token punctuation\">.</span><span class=\"token function\">log</span><span class=\"token punctuation\">(</span><span class=\"token template-string\"><span class=\"token template-punctuation string\">`</span><span class=\"token string\">Server is running on port </span><span class=\"token interpolation\"><span class=\"token interpolation-punctuation punctuation\">${</span><span class=\"token constant\">PORT</span><span class=\"token interpolation-punctuation punctuation\">}</span></span><span class=\"token template-punctuation string\">`</span></span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span></code></pre></div>\n<h1 id=\"how-to-implement-user-authentication-in-nodejs\" style=\"position:relative;\"><a href=\"#how-to-implement-user-authentication-in-nodejs\" aria-label=\"how to implement user authentication in nodejs permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>How to Implement User Authentication in Node.js</strong></h1>\n<h2 id=\"backend-implementation\" style=\"position:relative;\"><a href=\"#backend-implementation\" aria-label=\"backend implementation permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Backend Implementation</strong></h2>\n<h3 id=\"step-1-user-registration-process\" style=\"position:relative;\"><a href=\"#step-1-user-registration-process\" aria-label=\"step 1 user registration process permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Step 1: User Registration Process</strong></h3>\n<p>To securely register users, start by creating a Mongoose schema with fields for name, email, and password. Then, hash the password with <code class=\"language-text\">bcrypt</code> before saving it to enhance security. Finally, include basic validation to ensure required fields and unique email entries. To implement this setup, write the following code:</p>\n<h3 id=\"usermodeljsmodels\" style=\"position:relative;\"><a href=\"#usermodeljsmodels\" aria-label=\"usermodeljsmodels permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>userModel.js/Models</strong></h3>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"66514788688901370000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`const mongoose = require('mongoose');\nconst bcrypt = require('bcryptjs');\n\nconst userSchema = new mongoose.Schema({\n     name: { type: String, required: true },\n     email: { type: String, required: true, unique: true },\n     password: { type: String, required: true },\n   });\n\n// Hash password before saving\nuserSchema.pre('save', async function (next) {\n     if (!this.isModified('password')) return next();\n     this.password = await bcrypt.hash(this.password, 10);\n     next();\n   });\n\nmodule.exports = mongoose.model('User', userSchema);`, `66514788688901370000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"typescript\"><pre class=\"language-typescript\"><code class=\"language-typescript\"><span class=\"token keyword\">const</span> mongoose <span class=\"token operator\">=</span> <span class=\"token keyword\">require</span><span class=\"token punctuation\">(</span><span class=\"token string\">'mongoose'</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">const</span> bcrypt <span class=\"token operator\">=</span> <span class=\"token keyword\">require</span><span class=\"token punctuation\">(</span><span class=\"token string\">'bcryptjs'</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n<span class=\"token keyword\">const</span> userSchema <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">mongoose</span><span class=\"token punctuation\">.</span><span class=\"token function\">Schema</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span>\n     name<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span> type<span class=\"token operator\">:</span> String<span class=\"token punctuation\">,</span> required<span class=\"token operator\">:</span> <span class=\"token boolean\">true</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span>\n     email<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span> type<span class=\"token operator\">:</span> String<span class=\"token punctuation\">,</span> required<span class=\"token operator\">:</span> <span class=\"token boolean\">true</span><span class=\"token punctuation\">,</span> unique<span class=\"token operator\">:</span> <span class=\"token boolean\">true</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span>\n     password<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span> type<span class=\"token operator\">:</span> String<span class=\"token punctuation\">,</span> required<span class=\"token operator\">:</span> <span class=\"token boolean\">true</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span>\n   <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n<span class=\"token comment\">// Hash password before saving</span>\nuserSchema<span class=\"token punctuation\">.</span><span class=\"token function\">pre</span><span class=\"token punctuation\">(</span><span class=\"token string\">'save'</span><span class=\"token punctuation\">,</span> <span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token punctuation\">(</span>next<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n     <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span><span class=\"token keyword\">this</span><span class=\"token punctuation\">.</span><span class=\"token function\">isModified</span><span class=\"token punctuation\">(</span><span class=\"token string\">'password'</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> <span class=\"token function\">next</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n     <span class=\"token keyword\">this</span><span class=\"token punctuation\">.</span>password <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> bcrypt<span class=\"token punctuation\">.</span><span class=\"token function\">hash</span><span class=\"token punctuation\">(</span><span class=\"token keyword\">this</span><span class=\"token punctuation\">.</span>password<span class=\"token punctuation\">,</span> <span class=\"token number\">10</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n     <span class=\"token function\">next</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\nmodule<span class=\"token punctuation\">.</span>exports <span class=\"token operator\">=</span> mongoose<span class=\"token punctuation\">.</span><span class=\"token function\">model</span><span class=\"token punctuation\">(</span><span class=\"token string\">'User'</span><span class=\"token punctuation\">,</span> userSchema<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span></code></pre></div>\n<h3 id=\"step-2-login-and-session-management\" style=\"position:relative;\"><a href=\"#step-2-login-and-session-management\" aria-label=\"step 2 login and session management permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Step 2: Login and Session Management</strong></h3>\n<p>To set up a secure login flow, validate user credentials by checking the stored hashed password in the database. JWT tokens will be used to maintain stateless sessions and manage token expiration, adding an extra layer of security. To implement this, write the following code in <code class=\"language-text\">Auth.js/Routes</code>:</p>\n<h3 id=\"authjsroutes\" style=\"position:relative;\"><a href=\"#authjsroutes\" aria-label=\"authjsroutes permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Auth.js/Routes</strong></h3>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"44603457718107610000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`const express = require('express');\nconst User = require('../models/User');\nconst jwt = require('jsonwebtoken');\nconst bcrypt = require('bcryptjs');\nconst router = express.Router();\n\n\n// Register a new user\nrouter.post('/register', async (req, res) => {\n     const {name, email, password} = req.body;\n     try{\n         const newUser = new User({ name, email, password });\n         await newUser.save();\n         res.status(201).json({message: 'User registered successfully' });\n     } catch (error) {\n         res.status(400).json({ error: 'User already exists' });\n     }\n});\n\n\n//Login user and generate JWT token\nrouter.post('/login', async (req, res) => {\n     const { email, password } = req.body;\n     try{\n         const user = await User.findOne({ email });\n         if (!User) return res.status(404).json({ error: 'User not found'});\n\n         const isMatch = await bcrypt.compare(password, user.password);\n         if (!isMatch) return res.status(401).json({ error: 'Invalid credentials' });\n\n         const token = jwt.sign({ userId: user.\\_id }, process.env.JWT\\_SECRET, { expiresIn: '1h'});\n         res.json({ token });\n     } catch (error) {\n         res.status(500).json({ error: 'Server error' });\n     }\n});\n\nmodule.exports = router;`, `44603457718107610000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"typescript\"><pre class=\"language-typescript\"><code class=\"language-typescript\"><span class=\"token keyword\">const</span> express <span class=\"token operator\">=</span> <span class=\"token keyword\">require</span><span class=\"token punctuation\">(</span><span class=\"token string\">'express'</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">const</span> User <span class=\"token operator\">=</span> <span class=\"token keyword\">require</span><span class=\"token punctuation\">(</span><span class=\"token string\">'../models/User'</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">const</span> jwt <span class=\"token operator\">=</span> <span class=\"token keyword\">require</span><span class=\"token punctuation\">(</span><span class=\"token string\">'jsonwebtoken'</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">const</span> bcrypt <span class=\"token operator\">=</span> <span class=\"token keyword\">require</span><span class=\"token punctuation\">(</span><span class=\"token string\">'bcryptjs'</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">const</span> router <span class=\"token operator\">=</span> express<span class=\"token punctuation\">.</span><span class=\"token function\">Router</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n\n<span class=\"token comment\">// Register a new user</span>\nrouter<span class=\"token punctuation\">.</span><span class=\"token function\">post</span><span class=\"token punctuation\">(</span><span class=\"token string\">'/register'</span><span class=\"token punctuation\">,</span> <span class=\"token keyword\">async</span> <span class=\"token punctuation\">(</span>req<span class=\"token punctuation\">,</span> res<span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n     <span class=\"token keyword\">const</span> <span class=\"token punctuation\">{</span>name<span class=\"token punctuation\">,</span> email<span class=\"token punctuation\">,</span> password<span class=\"token punctuation\">}</span> <span class=\"token operator\">=</span> req<span class=\"token punctuation\">.</span>body<span class=\"token punctuation\">;</span>\n     <span class=\"token keyword\">try</span><span class=\"token punctuation\">{</span>\n         <span class=\"token keyword\">const</span> newUser <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">User</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> name<span class=\"token punctuation\">,</span> email<span class=\"token punctuation\">,</span> password <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n         <span class=\"token keyword\">await</span> newUser<span class=\"token punctuation\">.</span><span class=\"token function\">save</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n         res<span class=\"token punctuation\">.</span><span class=\"token function\">status</span><span class=\"token punctuation\">(</span><span class=\"token number\">201</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span>message<span class=\"token operator\">:</span> <span class=\"token string\">'User registered successfully'</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n     <span class=\"token punctuation\">}</span> <span class=\"token keyword\">catch</span> <span class=\"token punctuation\">(</span>error<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n         res<span class=\"token punctuation\">.</span><span class=\"token function\">status</span><span class=\"token punctuation\">(</span><span class=\"token number\">400</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> error<span class=\"token operator\">:</span> <span class=\"token string\">'User already exists'</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n     <span class=\"token punctuation\">}</span>\n<span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n\n<span class=\"token comment\">//Login user and generate JWT token</span>\nrouter<span class=\"token punctuation\">.</span><span class=\"token function\">post</span><span class=\"token punctuation\">(</span><span class=\"token string\">'/login'</span><span class=\"token punctuation\">,</span> <span class=\"token keyword\">async</span> <span class=\"token punctuation\">(</span>req<span class=\"token punctuation\">,</span> res<span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n     <span class=\"token keyword\">const</span> <span class=\"token punctuation\">{</span> email<span class=\"token punctuation\">,</span> password <span class=\"token punctuation\">}</span> <span class=\"token operator\">=</span> req<span class=\"token punctuation\">.</span>body<span class=\"token punctuation\">;</span>\n     <span class=\"token keyword\">try</span><span class=\"token punctuation\">{</span>\n         <span class=\"token keyword\">const</span> user <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> User<span class=\"token punctuation\">.</span><span class=\"token function\">findOne</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> email <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n         <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>User<span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> res<span class=\"token punctuation\">.</span><span class=\"token function\">status</span><span class=\"token punctuation\">(</span><span class=\"token number\">404</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> error<span class=\"token operator\">:</span> <span class=\"token string\">'User not found'</span><span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n         <span class=\"token keyword\">const</span> isMatch <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> bcrypt<span class=\"token punctuation\">.</span><span class=\"token function\">compare</span><span class=\"token punctuation\">(</span>password<span class=\"token punctuation\">,</span> user<span class=\"token punctuation\">.</span>password<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n         <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>isMatch<span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> res<span class=\"token punctuation\">.</span><span class=\"token function\">status</span><span class=\"token punctuation\">(</span><span class=\"token number\">401</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> error<span class=\"token operator\">:</span> <span class=\"token string\">'Invalid credentials'</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n         <span class=\"token keyword\">const</span> token <span class=\"token operator\">=</span> jwt<span class=\"token punctuation\">.</span><span class=\"token function\">sign</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> userId<span class=\"token operator\">:</span> user<span class=\"token punctuation\">.</span>\\_id <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span> process<span class=\"token punctuation\">.</span>env<span class=\"token punctuation\">.</span><span class=\"token constant\">JWT</span>\\_SECRET<span class=\"token punctuation\">,</span> <span class=\"token punctuation\">{</span> expiresIn<span class=\"token operator\">:</span> <span class=\"token string\">'1h'</span><span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n         res<span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> token <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n     <span class=\"token punctuation\">}</span> <span class=\"token keyword\">catch</span> <span class=\"token punctuation\">(</span>error<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n         res<span class=\"token punctuation\">.</span><span class=\"token function\">status</span><span class=\"token punctuation\">(</span><span class=\"token number\">500</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> error<span class=\"token operator\">:</span> <span class=\"token string\">'Server error'</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n     <span class=\"token punctuation\">}</span>\n<span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\nmodule<span class=\"token punctuation\">.</span>exports <span class=\"token operator\">=</span> router<span class=\"token punctuation\">;</span></code></pre></div>\n<h3 id=\"step-3-protecting-routes-with-middleware\" style=\"position:relative;\"><a href=\"#step-3-protecting-routes-with-middleware\" aria-label=\"step 3 protecting routes with middleware permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Step 3: Protecting Routes with Middleware</strong></h3>\n<p>To restrict access to certain routes, middleware is used to ensure only authenticated users can access specific pages or data. The following code demonstrates a middleware function that checks for a valid token, verifies it, and grants access if authenticated. Write this code in <code class=\"language-text\">Auth.js/Middleware</code>:</p>\n<h3 id=\"authjsmiddleware\" style=\"position:relative;\"><a href=\"#authjsmiddleware\" aria-label=\"authjsmiddleware permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Auth.js/Middleware</strong></h3>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"84467697158993070000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`const jwt = require('jsonwebtoken');\n\nconst auth = (req, res, next) => {\n     const token = req.header('Authorization')?.split(' ')[1];\n     if (!token) return res.status(401).json({ error: 'Access denied. No token provided.' });\n\n     try {\n         const decode = jwt.verify(token, process.env.JWT\\_SECRET);\n         req.user = decode;\n         next();\n     } catch (error) {\n         res.status(400).json({ error: 'Invalid Token' });\n     }\n};\n\nmodule.exports = auth;`, `84467697158993070000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"typescript\"><pre class=\"language-typescript\"><code class=\"language-typescript\"><span class=\"token keyword\">const</span> jwt <span class=\"token operator\">=</span> <span class=\"token keyword\">require</span><span class=\"token punctuation\">(</span><span class=\"token string\">'jsonwebtoken'</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n<span class=\"token keyword\">const</span> <span class=\"token function-variable function\">auth</span> <span class=\"token operator\">=</span> <span class=\"token punctuation\">(</span>req<span class=\"token punctuation\">,</span> res<span class=\"token punctuation\">,</span> next<span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n     <span class=\"token keyword\">const</span> token <span class=\"token operator\">=</span> req<span class=\"token punctuation\">.</span><span class=\"token function\">header</span><span class=\"token punctuation\">(</span><span class=\"token string\">'Authorization'</span><span class=\"token punctuation\">)</span><span class=\"token operator\">?.</span><span class=\"token function\">split</span><span class=\"token punctuation\">(</span><span class=\"token string\">' '</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">[</span><span class=\"token number\">1</span><span class=\"token punctuation\">]</span><span class=\"token punctuation\">;</span>\n     <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>token<span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> res<span class=\"token punctuation\">.</span><span class=\"token function\">status</span><span class=\"token punctuation\">(</span><span class=\"token number\">401</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> error<span class=\"token operator\">:</span> <span class=\"token string\">'Access denied. No token provided.'</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n     <span class=\"token keyword\">try</span> <span class=\"token punctuation\">{</span>\n         <span class=\"token keyword\">const</span> decode <span class=\"token operator\">=</span> jwt<span class=\"token punctuation\">.</span><span class=\"token function\">verify</span><span class=\"token punctuation\">(</span>token<span class=\"token punctuation\">,</span> process<span class=\"token punctuation\">.</span>env<span class=\"token punctuation\">.</span><span class=\"token constant\">JWT</span>\\_SECRET<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n         req<span class=\"token punctuation\">.</span>user <span class=\"token operator\">=</span> decode<span class=\"token punctuation\">;</span>\n         <span class=\"token function\">next</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n     <span class=\"token punctuation\">}</span> <span class=\"token keyword\">catch</span> <span class=\"token punctuation\">(</span>error<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n         res<span class=\"token punctuation\">.</span><span class=\"token function\">status</span><span class=\"token punctuation\">(</span><span class=\"token number\">400</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> error<span class=\"token operator\">:</span> <span class=\"token string\">'Invalid Token'</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n     <span class=\"token punctuation\">}</span>\n<span class=\"token punctuation\">}</span><span class=\"token punctuation\">;</span>\n\nmodule<span class=\"token punctuation\">.</span>exports <span class=\"token operator\">=</span> auth<span class=\"token punctuation\">;</span></code></pre></div>\n<p>This middleware function <code class=\"language-text\">auth</code> verifies if the request contains a valid JSON Web Token (JWT) in the authorization header. It checks for the token, verifies it using the secret key, and either allows access by calling <code class=\"language-text\">next()</code> or denies access if the token is invalid or missing.</p>\n<p>For implementing registration and login with JWT generation, add the following routes in <code class=\"language-text\">Auth.js/Routes</code>:</p>\n<h3 id=\"authjsroutes-1\" style=\"position:relative;\"><a href=\"#authjsroutes-1\" aria-label=\"authjsroutes 1 permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Auth.js/Routes</strong></h3>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"72573543519328190000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`const express = require('express');\nconst User = require('../models/User');\nconst jwt = require('jsonwebtoken');\nconst bcrypt = require('bcryptjs');\nconst router = express.Router();\n\n\n// Register a new user\nrouter.post('/register', async (req, res) => {\n     const {name, email, password} = req.body;\n     try{\n         const newUser = new User({ name, email, password });\n         await newUser.save();\n         res.status(201).json({message: 'User registered successfully' });\n     } catch (error) {\n         res.status(400).json({ error: 'User already exists' });\n     }\n});\n\n\n//Login user and generate JWT token\nrouter.post('/login', async (req, res) => {\n     const { email, password } = req.body;\n     try{\n         const user = await User.findOne({ email });\n         if (!User) return res.status(404).json({ error: 'User not found'});\n\n         const isMatch = await bcrypt.compare(password, user.password);\n         if (!isMatch) return res.status(401).json({ error: 'Invalid credentials' });\n\n         const token = jwt.sign({ userId: user.\\_id }, process.env.JWT\\_SECRET, { expiresIn: '1h'});\n         res.json({ token });\n     } catch (error) {\n         res.status(500).json({ error: 'Server error' });\n     }\n});\n\nmodule.exports = router;`, `72573543519328190000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"typescript\"><pre class=\"language-typescript\"><code class=\"language-typescript\"><span class=\"token keyword\">const</span> express <span class=\"token operator\">=</span> <span class=\"token keyword\">require</span><span class=\"token punctuation\">(</span><span class=\"token string\">'express'</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">const</span> User <span class=\"token operator\">=</span> <span class=\"token keyword\">require</span><span class=\"token punctuation\">(</span><span class=\"token string\">'../models/User'</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">const</span> jwt <span class=\"token operator\">=</span> <span class=\"token keyword\">require</span><span class=\"token punctuation\">(</span><span class=\"token string\">'jsonwebtoken'</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">const</span> bcrypt <span class=\"token operator\">=</span> <span class=\"token keyword\">require</span><span class=\"token punctuation\">(</span><span class=\"token string\">'bcryptjs'</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">const</span> router <span class=\"token operator\">=</span> express<span class=\"token punctuation\">.</span><span class=\"token function\">Router</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n\n<span class=\"token comment\">// Register a new user</span>\nrouter<span class=\"token punctuation\">.</span><span class=\"token function\">post</span><span class=\"token punctuation\">(</span><span class=\"token string\">'/register'</span><span class=\"token punctuation\">,</span> <span class=\"token keyword\">async</span> <span class=\"token punctuation\">(</span>req<span class=\"token punctuation\">,</span> res<span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n     <span class=\"token keyword\">const</span> <span class=\"token punctuation\">{</span>name<span class=\"token punctuation\">,</span> email<span class=\"token punctuation\">,</span> password<span class=\"token punctuation\">}</span> <span class=\"token operator\">=</span> req<span class=\"token punctuation\">.</span>body<span class=\"token punctuation\">;</span>\n     <span class=\"token keyword\">try</span><span class=\"token punctuation\">{</span>\n         <span class=\"token keyword\">const</span> newUser <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">User</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> name<span class=\"token punctuation\">,</span> email<span class=\"token punctuation\">,</span> password <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n         <span class=\"token keyword\">await</span> newUser<span class=\"token punctuation\">.</span><span class=\"token function\">save</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n         res<span class=\"token punctuation\">.</span><span class=\"token function\">status</span><span class=\"token punctuation\">(</span><span class=\"token number\">201</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span>message<span class=\"token operator\">:</span> <span class=\"token string\">'User registered successfully'</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n     <span class=\"token punctuation\">}</span> <span class=\"token keyword\">catch</span> <span class=\"token punctuation\">(</span>error<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n         res<span class=\"token punctuation\">.</span><span class=\"token function\">status</span><span class=\"token punctuation\">(</span><span class=\"token number\">400</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> error<span class=\"token operator\">:</span> <span class=\"token string\">'User already exists'</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n     <span class=\"token punctuation\">}</span>\n<span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n\n<span class=\"token comment\">//Login user and generate JWT token</span>\nrouter<span class=\"token punctuation\">.</span><span class=\"token function\">post</span><span class=\"token punctuation\">(</span><span class=\"token string\">'/login'</span><span class=\"token punctuation\">,</span> <span class=\"token keyword\">async</span> <span class=\"token punctuation\">(</span>req<span class=\"token punctuation\">,</span> res<span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n     <span class=\"token keyword\">const</span> <span class=\"token punctuation\">{</span> email<span class=\"token punctuation\">,</span> password <span class=\"token punctuation\">}</span> <span class=\"token operator\">=</span> req<span class=\"token punctuation\">.</span>body<span class=\"token punctuation\">;</span>\n     <span class=\"token keyword\">try</span><span class=\"token punctuation\">{</span>\n         <span class=\"token keyword\">const</span> user <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> User<span class=\"token punctuation\">.</span><span class=\"token function\">findOne</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> email <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n         <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>User<span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> res<span class=\"token punctuation\">.</span><span class=\"token function\">status</span><span class=\"token punctuation\">(</span><span class=\"token number\">404</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> error<span class=\"token operator\">:</span> <span class=\"token string\">'User not found'</span><span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n         <span class=\"token keyword\">const</span> isMatch <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> bcrypt<span class=\"token punctuation\">.</span><span class=\"token function\">compare</span><span class=\"token punctuation\">(</span>password<span class=\"token punctuation\">,</span> user<span class=\"token punctuation\">.</span>password<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n         <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>isMatch<span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> res<span class=\"token punctuation\">.</span><span class=\"token function\">status</span><span class=\"token punctuation\">(</span><span class=\"token number\">401</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> error<span class=\"token operator\">:</span> <span class=\"token string\">'Invalid credentials'</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n         <span class=\"token keyword\">const</span> token <span class=\"token operator\">=</span> jwt<span class=\"token punctuation\">.</span><span class=\"token function\">sign</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> userId<span class=\"token operator\">:</span> user<span class=\"token punctuation\">.</span>\\_id <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span> process<span class=\"token punctuation\">.</span>env<span class=\"token punctuation\">.</span><span class=\"token constant\">JWT</span>\\_SECRET<span class=\"token punctuation\">,</span> <span class=\"token punctuation\">{</span> expiresIn<span class=\"token operator\">:</span> <span class=\"token string\">'1h'</span><span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n         res<span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> token <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n     <span class=\"token punctuation\">}</span> <span class=\"token keyword\">catch</span> <span class=\"token punctuation\">(</span>error<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n         res<span class=\"token punctuation\">.</span><span class=\"token function\">status</span><span class=\"token punctuation\">(</span><span class=\"token number\">500</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> error<span class=\"token operator\">:</span> <span class=\"token string\">'Server error'</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n     <span class=\"token punctuation\">}</span>\n<span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\nmodule<span class=\"token punctuation\">.</span>exports <span class=\"token operator\">=</span> router<span class=\"token punctuation\">;</span></code></pre></div>\n<h2 id=\"frontend-implementation\" style=\"position:relative;\"><a href=\"#frontend-implementation\" aria-label=\"frontend implementation permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Frontend Implementation</strong></h2>\n<p>Finally, to create a simple login form that authenticates users, use the following code:</p>\n<h3 id=\"loginjs\" style=\"position:relative;\"><a href=\"#loginjs\" aria-label=\"loginjs permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Login.js</strong></h3>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"86993679369528500000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`import React, { useState } from 'react';\nimport axios from 'axios';\n\nfunction Login({ onLogin }) { // Accept onLogin as a prop\n   const [email, setEmail] = useState('');\n   const [password, setPassword] = useState('');\n   const [message, setMessage] = useState('');\n\n   const handleSubmit = async (e) => {\n     e.preventDefault(); // Prevents the page from refreshing on form submission\n\n     try {\n       const { data } = await axios.post('http://localhost:5000/api/auth/login', {\n         email,\n         password\n       });\n       localStorage.setItem('token', data.token); // Store JWT in localStorage\n       setMessage('Login Successful');\n       onLogin(); // Call onLogin to inform the App component of the login status\n     } catch (error) {\n       setMessage('Login failed. Check your credentials.');\n     }\n   };\n\n   return (\n     <div>\n       <h2>Login</h2>\n       <form onSubmit={handleSubmit}>\n         <input\n           type='email'\n           placeholder='Email'\n           value={email}\n           onChange={(e) => setEmail(e.target.value)}\n         />\n         <input\n           type='password'\n           placeholder='Password'\n           value={password}\n           onChange={(e) => setPassword(e.target.value)}\n         />\n         <button type='submit'>Login</button>\n       </form>\n       <p>{message}</p>\n     </div>\n   );\n}\n\nexport default Login;`, `86993679369528500000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"typescript\"><pre class=\"language-typescript\"><code class=\"language-typescript\"><span class=\"token keyword\">import</span> React<span class=\"token punctuation\">,</span> <span class=\"token punctuation\">{</span> useState <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'react'</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">import</span> axios <span class=\"token keyword\">from</span> <span class=\"token string\">'axios'</span><span class=\"token punctuation\">;</span>\n\n<span class=\"token keyword\">function</span> <span class=\"token function\">Login</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> onLogin <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span> <span class=\"token comment\">// Accept onLogin as a prop</span>\n   <span class=\"token keyword\">const</span> <span class=\"token punctuation\">[</span>email<span class=\"token punctuation\">,</span> setEmail<span class=\"token punctuation\">]</span> <span class=\"token operator\">=</span> <span class=\"token function\">useState</span><span class=\"token punctuation\">(</span><span class=\"token string\">''</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token keyword\">const</span> <span class=\"token punctuation\">[</span>password<span class=\"token punctuation\">,</span> setPassword<span class=\"token punctuation\">]</span> <span class=\"token operator\">=</span> <span class=\"token function\">useState</span><span class=\"token punctuation\">(</span><span class=\"token string\">''</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token keyword\">const</span> <span class=\"token punctuation\">[</span>message<span class=\"token punctuation\">,</span> setMessage<span class=\"token punctuation\">]</span> <span class=\"token operator\">=</span> <span class=\"token function\">useState</span><span class=\"token punctuation\">(</span><span class=\"token string\">''</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n   <span class=\"token keyword\">const</span> <span class=\"token function-variable function\">handleSubmit</span> <span class=\"token operator\">=</span> <span class=\"token keyword\">async</span> <span class=\"token punctuation\">(</span>e<span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n     e<span class=\"token punctuation\">.</span><span class=\"token function\">preventDefault</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span> <span class=\"token comment\">// Prevents the page from refreshing on form submission</span>\n\n     <span class=\"token keyword\">try</span> <span class=\"token punctuation\">{</span>\n       <span class=\"token keyword\">const</span> <span class=\"token punctuation\">{</span> data <span class=\"token punctuation\">}</span> <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> axios<span class=\"token punctuation\">.</span><span class=\"token function\">post</span><span class=\"token punctuation\">(</span><span class=\"token string\">'http://localhost:5000/api/auth/login'</span><span class=\"token punctuation\">,</span> <span class=\"token punctuation\">{</span>\n         email<span class=\"token punctuation\">,</span>\n         password\n       <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n       localStorage<span class=\"token punctuation\">.</span><span class=\"token function\">setItem</span><span class=\"token punctuation\">(</span><span class=\"token string\">'token'</span><span class=\"token punctuation\">,</span> data<span class=\"token punctuation\">.</span>token<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span> <span class=\"token comment\">// Store JWT in localStorage</span>\n       <span class=\"token function\">setMessage</span><span class=\"token punctuation\">(</span><span class=\"token string\">'Login Successful'</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n       <span class=\"token function\">onLogin</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span> <span class=\"token comment\">// Call onLogin to inform the App component of the login status</span>\n     <span class=\"token punctuation\">}</span> <span class=\"token keyword\">catch</span> <span class=\"token punctuation\">(</span>error<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n       <span class=\"token function\">setMessage</span><span class=\"token punctuation\">(</span><span class=\"token string\">'Login failed. Check your credentials.'</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n     <span class=\"token punctuation\">}</span>\n   <span class=\"token punctuation\">}</span><span class=\"token punctuation\">;</span>\n\n   <span class=\"token keyword\">return</span> <span class=\"token punctuation\">(</span>\n     <span class=\"token operator\">&lt;</span>div<span class=\"token operator\">></span>\n       <span class=\"token operator\">&lt;</span>h2<span class=\"token operator\">></span>Login<span class=\"token operator\">&lt;</span><span class=\"token operator\">/</span>h2<span class=\"token operator\">></span>\n       <span class=\"token operator\">&lt;</span>form onSubmit<span class=\"token operator\">=</span><span class=\"token punctuation\">{</span>handleSubmit<span class=\"token punctuation\">}</span><span class=\"token operator\">></span>\n         <span class=\"token operator\">&lt;</span>input\n           type<span class=\"token operator\">=</span><span class=\"token string\">'email'</span>\n           placeholder<span class=\"token operator\">=</span><span class=\"token string\">'Email'</span>\n           value<span class=\"token operator\">=</span><span class=\"token punctuation\">{</span>email<span class=\"token punctuation\">}</span>\n           onChange<span class=\"token operator\">=</span><span class=\"token punctuation\">{</span><span class=\"token punctuation\">(</span>e<span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token function\">setEmail</span><span class=\"token punctuation\">(</span>e<span class=\"token punctuation\">.</span>target<span class=\"token punctuation\">.</span>value<span class=\"token punctuation\">)</span><span class=\"token punctuation\">}</span>\n         <span class=\"token operator\">/</span><span class=\"token operator\">></span>\n         <span class=\"token operator\">&lt;</span>input\n           type<span class=\"token operator\">=</span><span class=\"token string\">'password'</span>\n           placeholder<span class=\"token operator\">=</span><span class=\"token string\">'Password'</span>\n           value<span class=\"token operator\">=</span><span class=\"token punctuation\">{</span>password<span class=\"token punctuation\">}</span>\n           onChange<span class=\"token operator\">=</span><span class=\"token punctuation\">{</span><span class=\"token punctuation\">(</span>e<span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token function\">setPassword</span><span class=\"token punctuation\">(</span>e<span class=\"token punctuation\">.</span>target<span class=\"token punctuation\">.</span>value<span class=\"token punctuation\">)</span><span class=\"token punctuation\">}</span>\n         <span class=\"token operator\">/</span><span class=\"token operator\">></span>\n         <span class=\"token operator\">&lt;</span>button type<span class=\"token operator\">=</span><span class=\"token string\">'submit'</span><span class=\"token operator\">></span>Login<span class=\"token operator\">&lt;</span><span class=\"token operator\">/</span>button<span class=\"token operator\">></span>\n       <span class=\"token operator\">&lt;</span><span class=\"token operator\">/</span>form<span class=\"token operator\">></span>\n       <span class=\"token operator\">&lt;</span>p<span class=\"token operator\">></span><span class=\"token punctuation\">{</span>message<span class=\"token punctuation\">}</span><span class=\"token operator\">&lt;</span><span class=\"token operator\">/</span>p<span class=\"token operator\">></span>\n     <span class=\"token operator\">&lt;</span><span class=\"token operator\">/</span>div<span class=\"token operator\">></span>\n   <span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">default</span> Login<span class=\"token punctuation\">;</span></code></pre></div>\n<h1 id=\"common-pitfalls-and-security-best-practices\" style=\"position:relative;\"><a href=\"#common-pitfalls-and-security-best-practices\" aria-label=\"common pitfalls and security best practices permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Common Pitfalls and Security Best Practices</strong></h1>\n<p>Building a secure authentication and authorization system requires more than just checking passwords and tokens. Developers must adopt a range of best practices to safeguard user data, prevent unauthorized access, and ensure smooth user experiences. This section highlights common vulnerabilities—like insecure password storage, session mismanagement, and token misuse—and provides practical solutions to address them effectively.</p>\n<h4 id=\"password-management\" style=\"position:relative;\"><a href=\"#password-management\" aria-label=\"password management permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Password Management</strong></h4>\n<ul>\n<li><strong>Avoid storing plain-text passwords:</strong> Store passwords securely using <strong>encryption techniques like hashing</strong>. Libraries such as <code class=\"language-text\">bcrypt</code> or <code class=\"language-text\">argon2</code> generate hashed passwords that are computationally infeasible to reverse. This way, even if attackers gain access to the database, the original passwords remain protected.</li>\n<li><strong>Regularly update password policies:</strong> Encourage the use of strong passwords and implement features like password expiration or complexity requirements to minimize vulnerabilities.</li>\n</ul>\n<h4 id=\"session-and-token-management\" style=\"position:relative;\"><a href=\"#session-and-token-management\" aria-label=\"session and token management permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Session and Token Management</strong></h4>\n<ul>\n<li><strong>Short <a href=\"https://www.linkedin.com/pulse/deciding-token-expiration-time-subramanian-krishnan/\" target=\"_blank\" rel=\"nofollow\">expiration times for tokens</a>:</strong> Use <strong>short-lived tokens</strong> to limit the risk from compromised credentials. For instance, access tokens may expire in 15 minutes, and refresh tokens should be rotated frequently.</li>\n<li><strong>Store sensitive information securely:</strong> Keep keys, secrets, and tokens safe by storing them in <strong>environment variables</strong>. Avoid hardcoding these sensitive values directly into the codebase to prevent exposure during development or deployment.</li>\n</ul>\n<h4 id=\"error-handling-and-feedback\" style=\"position:relative;\"><a href=\"#error-handling-and-feedback\" aria-label=\"error handling and feedback permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Error Handling and Feedback</strong></h4>\n<ul>\n<li><strong>Avoid exposing internal information:</strong> Carefully design error messages to prevent leaking critical system information. For example, avoid messages like “Invalid username or password” to prevent attackers from inferring valid usernames.</li>\n<li><strong>Provide user-friendly but secure responses:</strong> Make sure error messages offer users relevant feedback without revealing sensitive details.</li>\n</ul>\n<h4 id=\"using-https\" style=\"position:relative;\"><a href=\"#using-https\" aria-label=\"using https permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Using HTTPS</strong></h4>\n<ul>\n<li><strong>Encrypt all communication between clients and servers</strong> by using <strong>HTTPS</strong>. Encryption prevents sensitive data, such as login credentials or tokens, from being intercepted during transmission.</li>\n</ul>\n<h4 id=\"csrf-protection\" style=\"position:relative;\"><a href=\"#csrf-protection\" aria-label=\"csrf protection permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>CSRF Protection</strong></h4>\n<ul>\n<li><strong>Prevent <a href=\"https://portswigger.net/web-security/csrf\" target=\"_blank\" rel=\"nofollow\">Cross-Site Request Forgery (CSRF) attacks</a>:</strong> Use <strong>anti-CSRF tokens</strong> for requests that modify data (non-GET requests). Libraries like <code class=\"language-text\">csurf</code> for Express or built-in protection from tools like <strong>Supertokens</strong> can simplify the process​.</li>\n</ul>\n<h4 id=\"xss-protection\" style=\"position:relative;\"><a href=\"#xss-protection\" aria-label=\"xss protection permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>XSS Protection</strong></h4>\n<ul>\n<li><strong>Mitigate Cross-Site Scripting (XSS) risks:</strong> Use <strong>HttpOnly cookies</strong> to store tokens, ensuring they are inaccessible via JavaScript. This limits exposure to malicious scripts that might run on the client side. Additionally, validate user input and escape content properly to prevent injection attacks​.</li>\n</ul>\n<p>By following these best practices, developers can create more secure systems, safeguarding both user data and the application from common vulnerabilities.</p>\n<h1 id=\"simplify-authentication-with-supertokens\" style=\"position:relative;\"><a href=\"#simplify-authentication-with-supertokens\" aria-label=\"simplify authentication with supertokens permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Simplify Authentication with Supertokens</strong></h1>\n<h4 id=\"introduction-to-supertokens\" style=\"position:relative;\"><a href=\"#introduction-to-supertokens\" aria-label=\"introduction to supertokens permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Introduction to Supertokens</strong></h4>\n<p>Supertokens is a <strong>developer-friendly authentication platform</strong> designed to simplify the complexities of managing user sessions and secure access. It provides ready-made solutions for common challenges like <strong>user registration, login flows, session handling, and token management</strong>, so developers don’t have to build these systems from scratch. With a focus on efficiency and security, Supertokens offers both flexibility and scalability for applications of all sizes.</p>\n<h4 id=\"how-supertokens-helps\" style=\"position:relative;\"><a href=\"#how-supertokens-helps\" aria-label=\"how supertokens helps permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>How Supertokens Helps</strong></h4>\n<ul>\n<li><strong>Session Management Made Easy:</strong> Supertokens automatically handles <strong>JWT-based sessions</strong> and token rotation, eliminating the need for manual token configurations. This ensures <strong>stateless authentication</strong> with minimal setup.</li>\n<li><strong>Built-in Social Login:</strong> It includes support for social login providers such as <strong>Google and Facebook</strong>, allowing users to sign up seamlessly without complex custom configurations.</li>\n<li><strong>Multi-Factor Authentication (MFA):</strong> For applications that require <strong>stronger security</strong>, Supertokens provides support for <strong>MFA</strong> out of the box, offering advanced protection without adding unnecessary development overhead.</li>\n</ul>\n<h4 id=\"advantages-over-manual-implementation\" style=\"position:relative;\"><a href=\"#advantages-over-manual-implementation\" aria-label=\"advantages over manual implementation permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Advantages Over Manual Implementation</strong></h4>\n<ul>\n<li><strong>Development Efficiency:</strong> By providing <strong>secure, pre-built APIs</strong>, Supertokens reduces the amount of time needed to set up authentication and session management.</li>\n<li><strong>Reliable and Tested Authentication Flows:</strong> Supertokens ensures that <strong>authentication processes work consistently</strong> by adhering to best practices and implementing features like token rotation and expiration by default.</li>\n<li><strong>Lower Complexity:</strong> With Supertokens managing the backend intricacies of authentication, teams can <strong>focus on core application features</strong>, reducing complexity while maintaining security.</li>\n</ul>\n<h4 id=\"supertokens-security-protections-csrf-and-xss-mitigation\" style=\"position:relative;\"><a href=\"#supertokens-security-protections-csrf-and-xss-mitigation\" aria-label=\"supertokens security protections csrf and xss mitigation permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Supertokens’ Security Protections: CSRF and XSS Mitigation</strong></h4>\n<ul>\n<li><strong>CSRF Protection:</strong> Supertokens includes <strong>built-in CSRF protection</strong> for non-GET API routes. This ensures that only legitimate requests are processed, reducing the risk of unauthorized actions through cross-site request forgery attacks​.</li>\n<li><strong>XSS Protection:</strong> For enhanced session security, Supertokens uses <strong>HttpOnly cookies</strong> to store tokens, which prevents them from being accessed by JavaScript in case of an XSS attack​. This makes session management safer by mitigating the risks associated with script injections.</li>\n</ul>\n<p>Supertokens provides a secure, scalable solution that automates much of the work involved in authentication and session management. By implementing Supertokens, developers can ensure their applications are protected while also saving time and effort that would otherwise go into managing these systems manually.</p>\n<h1 id=\"conclusion\" style=\"position:relative;\"><a href=\"#conclusion\" aria-label=\"conclusion permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Conclusion</strong></h1>\n<p>Authentication and authorization are essential for building secure web applications, requiring developers to carefully balance <strong>security, usability, and performance</strong>. These components ensure that only verified users gain access to the system and that their actions are appropriately controlled through permissions. This article covered the fundamental steps to build a secure authentication system, focusing on <strong>user registration, login, session management, and role-based access control (RBAC)</strong> to manage user permissions effectively.</p>\n<p>For developers looking to streamline the implementation process, <strong>Supertokens</strong> offers a powerful, ready-to-use solution. It reduces the time and complexity of managing tokens, sessions, and user roles while incorporating <strong>advanced security features</strong> such as <strong>XSS and CSRF protection</strong>. Explore <a href=\"https://supertokens.com/product\" target=\"_blank\" rel=\"nofollow\">Supertokens</a> to <strong>simplify your authentication system</strong>, saving development effort and enhancing your application’s security and reliability​.</p>","frontmatter":{"date":"November 02, 2024","title":"How to Authenticate and Authorize Users in a Node.js Express App","cover":"user-authentication-in-node.png","author":"Mostafa Ibrahim","description":"A step by step guide on how to Authenticate and Authorize Users in a Node.js Express App"},"fields":{"slug":"/user-authentication-in-node/"}},"site":{"siteMetadata":{"title":"SuperTokens Blog"}}},"pageContext":{"id":"0d4d0aea-2efe-51ea-a6fc-1502bfd40c6f","fields__slug":"/user-authentication-in-node/","__params":{"fields__slug":"user-authentication-in-node"}}},
    "staticQueryHashes": []}