Today, I want to walk through the basics of JWTs (JSON Web Tokens). They show up on most modern websites, so understanding them is a helpful skill for any new developer.
The Old Way: Server-Side Sessions
To understand the importance of JWT, let's take a quick trip down memory lane: in the past, most sites used server-side sessions to keep users logged in, so every time a user signed in, the server had to create a session in memory or in a database, and then hand the user a cookie with a session ID. Also, every single request had to go back to that same server (or a shared session store) to look up that ID.
It worked, but it was a lot to deal with as systems grew. Managing sessions across multiple servers was messy — JWTs were designed to solve that.
What Are JWTs?
JWTs are a specific type of token that is lightweight and used to safely send user identity information between a client and a server in a JSON format. At a high level, the purpose of a JWT is to transport user identity and permissions securely between systems without storing session data on the server.
Think of a JWT like a dessert delivery with a security seal 🧁. The bakery seals the box when they pack it. Any bakery location can check the seal and read the order slip inside without calling the original shop.
Key Traits of JWTs
1. Self-containment
A JWT carries the essential user information (which are called claims) inside the token itself, just like the dessert delivery includes an order slip with your name and what you bought. The server doesn't need to check a database every time you make a request. The token already tells it what it needs to know.
2. Secure
JWTs are digitally signed, so the server can tell if someone tried to forge or modify them. For instance, if someone opens the delivery box and swaps out the order slip, the seal breaks in the process, so the bakery doesn't need to look anything up — the broken seal alone tells them the box was tampered with.
It’s important to note that JWTs are signed, not encrypted. That means anyone who gets the token can read its contents, but they can’t change them without breaking the signature.
3. Stateless
Servers do not store JWTs. They simply verify the signature whenever a request arrives with a token. It's like the bakery not keeping records of every delivery. If you show up at any location with your sealed dessert box, they check the seal and read the slip inside. If the seal is intact, they trust it and know the contents are legit.
What's Next?
We covered what JWTs are and their purpose. In the next blog post, we'll take a look at the anatomy of a JWT.
What's your experience with JWTs? Have you worked with them before? Let me know in the comments! 👇
Top comments (0)