JSON Web Tokens
Express.js·5 min read·Jan 1, 2025
A JSON Web Token (JWT) is a compact, self-contained, and digitally signed token that uses the JSON format to transmit information between parties, making it particularly suitable for the Web.
Just like Bearer tokens, JWTs are typically generated by the server in response to a successful login request and transmitted by the client through the Authorization header of the HTTP request using the Bearer Authentication scheme.
Authorization: Bearer <jwt>The difference with Bearer tokens
Although JSON Web Tokens and Bearer tokens are both used for authentication to gain access to protected resources and services, they serve different purposes and have different characteristics.
Statelessness
Once issued, JWTs contain all the necessary information within the token itself, including user identity and any necessary claims. This means that the server doesn't need to maintain any session state for the token to be valid.
Bearer tokens, on the other hand, often require the server to maintain some state, for example in-memory or in a database, to validate the token.
Security
JWTs can be digitally signed, providing a level of integrity and authenticity. This means that the server can verify that the token hasn't been tampered with and that it was indeed issued by a trusted authority, such as itself.
Bearer tokens, while they can also be secured using HTTPS, don't inherently provide this level of assurance without additional mechanisms.
Flexibility
JWTs are flexible in terms of the information they can carry. They can include custom claims beyond just the user identity, allowing for a wide range of use cases.
Bearer tokens typically contain a reference to a session or user ID, which may limit the flexibility of the authentication mechanism.
Interoperability
JWTs are a widely adopted standard with libraries available for most programming languages and platforms. This makes them easy to integrate into a variety of systems and ensures interoperability between different components of a distributed system.
The anatomy of JWTs
A JWT is composed of a header, a payload and a signature, each separated by a dot character:
Unlock the Build RESTful APIs in Node.js module
Learn how to build real database-backed and framework-powered RESTful APIs with MySQL, Sequelize, and Express.
You get immediate access to:
- 37 focused lessons across MySQL, Sequelize, backend, and Express
- 4 real-world projects with commented solutions
- Ongoing updates to this bundle
- Lifetime access to this bundle