Node.js server-side authentication: Tokens vs. JWT - LogRocket Blog (2024)

In modern web development, authentication is a critical part of securing applications. The two most popular approaches include server-side authentication using tokens and client-side authentication using JSON Web Tokens (JWT).

Node.js server-side authentication: Tokens vs. JWT - LogRocket Blog (1)

Both methods have their own unique advantages and disadvantages, and deciding which one to use depends on the requirements of your specific application. In this article, we’ll compare both methods and highlight the benefits and drawbacks of each. Let’s get started!

Jump ahead:

  • Stateless vs. stateful authentication
  • What are server-side tokens?
  • Advantages of using server-side authentication
  • Disadvantages of server-side authentication
  • Server-side authentication with a Node.js application
  • Server-side authentication: Use cases
  • What is JWT authentication?
  • Advantages of JWT authentication
  • Disadvantages of JWT authentication
  • JWT authentication with a Node.js application
  • JWT: Use cases
  • Server-side tokens vs. JWT: Summary

Stateless vs. stateful authentication

In web applications, authentication is the process of verifying the identity of a user who wants to access a restricted resource. You can use several different kinds of authentication, likeusername and password authentication, social login, or biometric authentication.

Stateless authentication

In stateless authentication, the server doesn’t store any session information about the user. Instead, each request that the user makes to the server contains all the necessary information for authentication, typically in the form of a JWT. The server then validates the token and responds accordingly.

Stateless authentication is popular in modern web applications because it is scalable and can be used with the microservices architecture.

Stateful authentication

In stateful authentication, the server stores session information about the user in a database or an in-memory cache. When the user logs in, the server creates a session ID and stores it on the server-side. This session ID is then used to authenticate subsequent requests made by the user.

Stateful authentication is less scalable than stateless authentication because it requires the server to maintain state, which can become an issue with large user bases.

What are server-side tokens?

Using server-side tokens, which is also called session-based authentication, is an example of stateful authentication that involves storing user authentication data on the server. Upon successful authentication, the server generates a unique token for the user, which is then stored in the server’s memory or database. The token is then sent back to the client, either as a cookie or in the response body.

Server-side authentication with tokens involves creating a unique session token for each user when they log in. The token is stored on the server-side and used to authenticate subsequent requests from the same user.

In contrast, client-side authentication using JWT involves issuing a signed token to the client upon successful login, which is then stored on the client-side and sent back to the server with each subsequent request.

Advantages of using server-side authentication

Easy to invalidate

Server-side authentication is easy to invalidate because we have complete control over the session data stored on the server. If we suspect any fraudulent activity, we can quickly terminate a user’s session or revoke a token, thereby providing an additional layer of security.

No storage limitations

Unlike client-side authentication, where storage space is limited to cookies or local storage, we can store any amount of session data on the server with server-side authentication. This makes it easier to store large amounts of data, like user preferences or history.

Better for compliance

To meet compliance regulations, some regulatory bodies require that session data be stored on the server-side. This is aimed at enhancing data security, privacy, and control over sensitive information within a controlled and secure environment. In these cases, server-side authentication is a better option.

Some examples include the Payment Card Industry Data Security Standard (PCI DSS) and the Health Insurance Portability and Accountability Act (HIPAA).

No need for re-authentication

With server-side authentication, you don’t need to re-authenticate the user on every request, which can improve your application’s performance.

Disadvantages of server-side authentication

Scalability issues

As the number of users and sessions increases, storing all the session data on the server can cause scalability issues. It requires more memory and CPU resources, which can cause slower response times and decrease performance overall.

Complexity

Server-side authentication can be complex to implement and maintain, especially if you need to store the session data across multiple servers or instances. It requires more code, configuration, and infrastructure.

Cost

Because it requires more resources and infrastructure, server-side authentication can be more expensive than client-side authentication.

More great articles from LogRocket:

  • Don't miss a moment with The Replay, a curated newsletter from LogRocket
  • Learn how LogRocket's Galileo cuts through the noise to proactively resolve issues in your app
  • Use React's useEffect to optimize your application's performance
  • Switch between multiple versions of Node
  • Discover how to use the React children prop with TypeScript
  • Explore creating a custom mouse cursor with CSS
  • Advisory boards aren’t just for executives. Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.

No offline access

Since all the session data is stored on the server, there is no offline access available, which can be a disadvantage in some scenarios.

Server-side authentication with a Node.js application

Let’s review a simple code implementation of the server-side authentication method. First, we need to install expresssession and the Express package for Node.js. We can do so by running the code below:

npm install express express-session

Next, we’ll create a simple index.js file:

const express = require("express");const session = require("express-session");const app = express();// Dummy user object to demonstrateconst users = [ { id: 1, username: "john", password: "password" }, { id: 2, username: "jane", password: "password" },];// Array to hold blacklisted user IDsconst blacklistedUsers = [];// Middleware to parse JSON request bodiesapp.use(express.json());// Middleware to initialize the sessionapp.use( session({ secret: "mysecretkey", resave: false, saveUninitialized: true, }));// Login endpointapp.post("/login", (req, res) => { const { username, password } = req.body; // Find the user by username and password const user = users.find( (u) => u.username === username && u.password === password ); if (user) { if (blacklistedUsers.includes(user.id)) { return res.status(403).send("User is blacklisted"); } // Save the user ID in the session req.session.userId = user.id; // Send the user object back to the client res.json({ user }); } else { // Send an error response if the user is not found res.status(401).json({ message: "Invalid username or password" }); }});// Logout endpointapp.post("/logout", (req, res) => { // Destroy the session to log the user out req.session.destroy(); // Send a success response res.json({ message: "Logged out successfully" });});// Protected endpointapp.get("/profile", (req, res) => { console.log(req.session.userId); // Check if the user is logged in by checking if the user ID is present in the session if (req.session.userId) { // Find the user by ID const user = users.find((u) => u.id === req.session.userId); // Send the user object back to the client res.json({ user }); } else { // Send an error response if the user is not logged in res.status(401).json({ message: "Unauthorized" }); }}); // Blacklist endpoint app.post("/blacklist", (req, res) => { const { userId } = req.body; blacklistedUsers.push(userId); res.send(`User ID ${userId} blacklisted`);});// Start the serverapp.listen(3000, () => { console.log("Server started on port 3000");});

The code above implements server-side authentication using Express and the express-session middleware. It defines a simple login and logout endpoint and a protected profile endpoint that can only be accessed by authenticated users.

When a user logs in with a valid username and password, their user ID is saved in the session. This user ID retrieves the user object from the array of dummy users and sends it back to the client. When the user logs out, their session is destroyed.

The protected profile endpoint checks if the user is logged in by checking if their user ID is present in the session. If the user is not logged in, an error response is sent. Otherwise, the user object is retrieved from the array of dummy users and sent back to the client.

One drawback of this implementation is that the session and blacklisted user is stored server-side in memory, which can become a scalability issue as the number of users increases. Additionally, if the server crashes or restarts, all active sessions will be lost. To avoid these issues, you could use a distributed caching system like Redis to store sessions instead of storing them in memory.

Server-side authentication: Use cases

Let’s review the scenarios where server-side authentication using tokens is generally preferable.

Security is a top priority

Because the server has full control over the creation and management of session tokens, it’s easier to implement advanced security measures, like IP blocking, rate limiting, and token revocation.

The application requires real-time updates

If your application requires real-time updates or notifications, server-side authentication can be more efficient because the server can push updates to the client based on the session ID.

Scalability is a concern

In server-side authentication, the session state is stored on the server-side, whichcan be scaled horizontally across multiple servers using tools like Redis or Memcached.

What is JWT authentication?

JWT authentication is a stateless, token-based authentication method. It involves generating a token containing the user’s identity information, which is then sent to the client to be stored. The client then sends this token with every request to the server to authenticate the user. To ensure that the user is authorized to access the requested resource, the token is verified on the server.

To implement client-side authentication using JWT, you’ll need to issue a signed token to the client upon successful login and store it on the client-side. You’ll also need to include the token with each subsequent request to authenticate the user.

Advantages of JWT authentication

Stateless

Since the token contains all the necessary information to authenticate the user, the server doesn’t need to maintain any session data or database queries. JWT is a stateless authentication method that can simplify server maintenance and reduce resource usage.

Scalability

JSON Web Tokens allow for scaling out server resources because the server doesn’t need to maintain any state data.

Cross-domain

The token is self-contained and doesn’t require accessing the server for validation, so JWT can be used across different domains.

Disadvantages of JWT authentication

Token size

In JWT authentication, the token size can be large. This can impact performance negatively, especially if the token is sent with every request.

Security risks

If a token is compromised, an attacker can impersonate the user and gain access to protected resources. Additionally, if the token is not properly signed, an attacker can modify the data contained in the token.

Token expiration

If the token doesn’t expire, it can be used indefinitely. However, if the token expires too frequently, it can inconvenience the users, who would have to log in frequently. Balancing the token expiration time is a critical aspect to consider.

JWT authentication with a Node.js application

The code below shows an example implementation of JWT authentication using Node.js and the Express framework:

const express = require("express");const jwt = require("jsonwebtoken");const app = express();// Dummy user object to demonstrateconst users = [ { id: 1, username: "john", password: "password" }, { id: 2, username: "jane", password: "password" },];// Secret key to sign and verify JWTsconst secretKey = "mysecretkey";// Login endpointapp.post("/login", (req, res) => { const { username, password } = req.body; // Find the user by username and password const user = users.find( (u) => u.username === username && u.password === password ); if (user) { // Create a JWT token with the user ID as the payload const token = jwt.sign({ userId: user.id }, secretKey); // Send the token back to the client res.json({ token }); } else { // Send an error response if the user is not found res.status(401).json({ message: "Invalid username or password" }); }});// Protected endpointapp.get("/profile", (req, res) => { // Get the authorization header from the request const authHeader = req.headers.authorization; if (authHeader) { // Extract the JWT token from the authorization header const token = authHeader.split(" ")[1]; try { // Verify the JWT token with the secret key const decodedToken = jwt.verify(token, secretKey); // Get the user ID from the decoded token const userId = decodedToken.userId; // Find the user by ID const user = users.find((u) => u.id === userId); // Send the user object back to the client res.json({ user }); } catch (error) { // Send an error response if the token is invalid res.status(401).json({ message: "Invalid token" }); } } else { // Send an error response if the authorization header is not present res.status(401).json({ message: "Unauthorized" }); }});// Start the serverapp.listen(3000, () => { console.log("Server started on port 3000");});

The code uses the jsonwebtoken library to generate and verify JSON Web Tokens. It provides two endpoints, /login and /profile.

The /login endpoint expects a POST request with the username and password of a user in the request body. It finds the user in the users array and creates a JWT token with the user ID as the payload. It then sends the token back to the client as a JSON object.

The /profile endpoint expects a GET request with an authorization header containing a valid JWT token. It extracts the token from the header and verifies it with the secret key. If the token is valid, it extracts the user ID from the payload and finds the user in the users array. It then sends the user object back to the client as a JSON object.

JWT: Use cases

Authentication and authorization

We can use JWTs to securely transmit authentication and authorization data between the client and server. By including a user’s identity and permissions in a JWT, a server can verify that a user is authorized to access certain resources.

Single sign-on (SSO)

JWTs are a great choice to implement single-sign on (SSO), where a user logs into a single application and is then able to access other applications without having to log in again. The JWT can securely transmit the user’s identity and authentication state between applications.

Mobile applications

Where traditional session-based authentication methods may not be feasible, you can use JWTs to authenticate and authorize users in mobile applications. The JWT can be stored on the device and used to authenticate the user with the server on subsequent requests.

Microservices

You can use JWTs to authenticate and authorize requests between microservices in a distributed system. Each microservice can use the JWT to verify that requests are coming from a trusted source and that the user is authorized to access the requested resource.

Server-side tokens vs. JWT: Summary

TokensJWT
Stored server-sideStored client-side
Easily revokedDifficult to revoke
Require server-side storageStateless
Suitable for real-timeBetter for mobile or SPA
UpdatesMultiple domains or microservices
Scalable with Redis or MemcachedRequires distributed signing or validation
More secureFaster and easier to implement

Conclusion

In summary, JWT authentication is a stateless approach that uses digitally signed tokens for secure communication. It offers easy integration, cross-domain compatibility, and additional security features. However, it’s important to keep an eye on the token size and revocation.

Server-side token authentication involves storing session information on the server. It offers easy session management, quick invalidation, and control over simultaneous logins. However, it requires server-side storage, which may pose scalability challenges.

Choosing between JWT and server-side token authentication depends on your use case, security needs, and scalability requirements. JWT is suitable for stateless scenarios and APIs, while server-side tokens work best for session-based authentication in web applications.

I hope you enjoyed this article, and be sure to leave a comment if you have any questions. Happy coding!

200s only Node.js server-side authentication: Tokens vs. JWT - LogRocket Blog (4) Monitor failed and slow network requests in production

Deploying a Node-based web app or website is the easy part. Making sure your Node instance continues to serve resources to your app is where things get tougher. If you’re interested in ensuring requests to the backend or third-party services are successful, try LogRocket.

LogRocket is like a DVR for web and mobile apps, recording literally everything that happens while a user interacts with your app. Instead of guessing why problems happen, you can aggregate and report on problematic network requests to quickly understand the root cause.

LogRocket instruments your app to record baseline performance timings such as page load time, time to first byte, slow network requests, and also logs Redux, NgRx, and Vuex actions/state. Start monitoring for free.

Node.js server-side authentication: Tokens vs. JWT - LogRocket Blog (2024)

FAQs

Why JWTs are bad for authentication? ›

JWTs which just store a simple session token are inefficient and less flexible than a regular session cookie, and don't gain you any advantage. The JWT specification itself is not trusted by security experts. This should preclude all usage of them for anything related to security and authentication.

What is the difference between JWT and token authentication? ›

Additionally, JWTs can be utilized across numerous domains and can be easily verified by different services without relying on a central authority. In contrast, normal token-based authentication requires the server to keep up the session state or store tokens in a database to approve them.

How does JWT work on the server side? ›

The server generates both an access token (JWT) and a refresh token. The access token has a relatively short expiration time while the refresh token has a longer expiration time. Then, the server sends the JWT and Refresh token to the client. The refresh token is usually stored in a secure cookie.

Is JWT good for API authentication? ›

Any API that requires authentication can easily switch over to JWT's authorization. With JWT authorization, you get a user-based authentication. Once the user is authenticated, the user gets a secure token that they can use on all systems. The management of the user (and therefore the token) is centralized.

What is replacing JWT? ›

Paseto, which stands for Platform-Agnostic Security Tokens, is a specification for secure stateless tokens. It provides a modern and better alternative to JWT, addressing some of its inherent vulnerabilities and emphasizing secure defaults and ease of implementation.

Is JWT obsolete? ›

The JWT app type will be completely deprecated as of June 2023. New and current users have 12 months to migrate their JWT based solutions to the Server-to-Server OAuth app type.

What are the disadvantages of JWT tokens? ›

Disadvantages of JWT Authentication:

Revoking a JWT before expiration requires additional complexity, such as token blacklisting. Security Risks: If the secret key used to sign JWTs is compromised, attackers can create forged tokens. It's crucial to safeguard this key.

Why use JWT over Basic Auth? ›

Basic Auth: Enables users to access APIs using username and password combinations encoded in the Authorization header. JWT Authentication: Allows secure access through JSON Web Tokens (JWTs) issued by your authorization server, containing user information and access claims.

Is OAuth more secure than JWT? ›

While OAuth provides a flexible authorization framework, JWT offers a compact way to represent user information securely. Combined, they form a potent combination for securing web applications, providing strong authentication and fine-grained access control.

What is the difference between JWT and server to server? ›

The Server-to-server OAuth app overcomes the following limitations of the JWT app: You can restrict the permissions on the token by providing scopes through the app. The token has a set expiration time of one hour (3600 seconds). You can create multiple Server-to-server OAuth apps in your account.

Why use JWT instead of session? ›

Choosing between JWT and session-based authentication depends on your application's specific needs. If you prioritize statelessness and scalability, JWT might be your go-to. For traditional applications where immediate control over sessions is crucial, session-based authentication holds the upper hand.

How to use JWT for authentication in node? ›

To do so, create a new file called authenticate. js on the project folder and put the following code in it: const jwt = require('jsonwebtoken'); module. exports = (req, res, next) => { const authHeader = req.

What is the best authentication for API? ›

Best API authentication protocols
  1. OAuth (Open Authorization) OAuth is an industry-standard authentication protocol that allows secure access to resources on behalf of a user or application. ...
  2. Bearer tokens. Bearer tokens are a simple way to authenticate API requests. ...
  3. API keys. ...
  4. JSON Web Tokens (JWT) ...
  5. Basic authentication.
Oct 25, 2023

Should I use JWT for authorization? ›

Use traditional session-based authentication. It's more secure and flexible than JWT. JWT is a good fit for cases/situations where you want to issue a one-time token to be used for a specific purpose.

What are the security issues with JWT? ›

One of the most significant weaknesses of JWTs is their lack of encryption. JWTs are designed to be compact and self-contained, which means that the data within them is not encrypted. While they can be signed to ensure data integrity, sensitive information within a JWT remains exposed in plaintext.

What are the disadvantages of JWT authentication? ›

Disadvantages of JWT Authentication:

Revoking a JWT before expiration requires additional complexity, such as token blacklisting. Security Risks: If the secret key used to sign JWTs is compromised, attackers can create forged tokens. It's crucial to safeguard this key.

What is the problem with JWT token? ›

JWT attacks involve a user sending modified JWTs to the server in order to achieve a malicious goal. Typically, this goal is to bypass authentication and access controls by impersonating another user who has already been authenticated.

What are the criticism of JWT? ›

The criticisms of JWT seem to fall into two categories: (1) Criticizing vulnerabilities in particular JWT libraries, as in this article. (2) Generally criticizing the practice of using any "stateless" client tokens. Because there's no great way to revoke them early while remaining stateless, etc.

Why security experts believe JWTs aren t safe for user sessions? ›

JWT's are often not encrypted so anyone able to perform a man-in-the-middle attack and sniff the JWT now has your authentication credentials. This is made easier because the MITM attack only needs to be completed on the connection between the server and the client.

Top Articles
Git Diff: How to Compare Files Between Two Branches
Find My Habitat — Habitat for Humanity Florida (Copy)
Friskies Tender And Crunchy Recall
Swimgs Yuzzle Wuzzle Yups Wits Sadie Plant Tune 3 Tabs Winnie The Pooh Halloween Bob The Builder Christmas Autumns Cow Dog Pig Tim Cook’s Birthday Buff Work It Out Wombats Pineview Playtime Chronicles Day Of The Dead The Alpha Baa Baa Twinkle
Live Basketball Scores Flashscore
Coverage of the introduction of the Water (Special Measures) Bill
9192464227
Die Windows GDI+ (Teil 1)
Craigslist Nj North Cars By Owner
Produzione mondiale di vino
Conduent Connect Feps Login
Obituary | Shawn Alexander | Russell Funeral Home, Inc.
Pittsburgh Ultra Advanced Stain And Sealant Color Chart
Uhcs Patient Wallet
Playgirl Magazine Cover Template Free
Curtains - Cheap Ready Made Curtains - Deconovo UK
Xxn Abbreviation List 2023
Sport-News heute – Schweiz & International | aktuell im Ticker
25Cc To Tbsp
Pekin Soccer Tournament
Officialmilarosee
CDL Rostermania 2023-2024 | News, Rumors & Every Confirmed Roster
Puss In Boots: The Last Wish Showtimes Near Cinépolis Vista
Raz-Plus Literacy Essentials for PreK-6
R. Kelly Net Worth 2024: The King Of R&B's Rise And Fall
Academy Sports Meridian Ms
Nesb Routing Number
Essence Healthcare Otc 2023 Catalog
Expression Home XP-452 | Grand public | Imprimantes jet d'encre | Imprimantes | Produits | Epson France
Stockton (California) – Travel guide at Wikivoyage
950 Sqft 2 BHK Villa for sale in Devi Redhills Sirinium | Red Hills, Chennai | Property ID - 15334774
Funky Town Gore Cartel Video
Rays Salary Cap
Bfri Forum
Mumu Player Pokemon Go
Kokomo Mugshots Busted
Craigslist In Myrtle Beach
Samsung 9C8
Labyrinth enchantment | PoE Wiki
What Does Code 898 Mean On Irs Transcript
Wayne State Academica Login
Dcilottery Login
VDJdb in 2019: database extension, new analysis infrastructure and a T-cell receptor motif compendium
Powerspec G512
The Many Faces of the Craigslist Killer
A rough Sunday for some of the NFL's best teams in 2023 led to the three biggest upsets: Analysis
Kaamel Hasaun Wikipedia
Aurora Southeast Recreation Center And Fieldhouse Reviews
Mail2World Sign Up
300 Fort Monroe Industrial Parkway Monroeville Oh
Southwind Village, Southend Village, Southwood Village, Supervision Of Alcohol Sales In Church And Village Halls
Craigs List Sarasota
Latest Posts
Article information

Author: Allyn Kozey

Last Updated:

Views: 5983

Rating: 4.2 / 5 (63 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Allyn Kozey

Birthday: 1993-12-21

Address: Suite 454 40343 Larson Union, Port Melia, TX 16164

Phone: +2456904400762

Job: Investor Administrator

Hobby: Sketching, Puzzles, Pet, Mountaineering, Skydiving, Dowsing, Sports

Introduction: My name is Allyn Kozey, I am a outstanding, colorful, adventurous, encouraging, zealous, tender, helpful person who loves writing and wants to share my knowledge and understanding with you.