JWT
- Node.js course
- Advanced
- Lesson 23/83
- 5 min
Learn JWT authentication with jsonwebtoken.
What is JWT?
JWT (JSON Web Token) is a signed string that carries information safely between two parties. It is commonly used for authentication: the user logs in, the server returns a JWT, and the client sends it with subsequent requests.
A JWT has three parts: header, payload, and signature. The signature is produced with a secret; so the token cannot be tampered with. In Node.js you create and verify JWTs with the jsonwebtoken module.
jwt.sign and jwt.verify
jwt.sign(payload, secret) produces a JWT. payload is an object (e.g. { user: "Alex" }); secret is the signing key. The returned token is a string.
jwt.verify(token, secret) validates the token and returns the payload. It throws if the signature is wrong. You can pass an expiry as a third argument: jwt.sign(payload, secret, { expiresIn: "1h" }) makes the token valid for one hour.
Practice Log the type of token
Import the jwt module. Produce a token with jwt.sign({ user: "Alex" }, "secret"). Log typeof token.
Starter code
// import the module
// produce a token
// log its typeSample solution
const jwt = require("jsonwebtoken");
const token = jwt.sign({ user: "Alex" }, "secret");
console.log(typeof token);Expected output
string
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the module name
const jwt = require("____")
const jwt = require("jsonwebtoken")
Explanation: The jsonwebtoken module loads as 'jsonwebtoken'.
2 Match each piece to its role
| Term | Meaning |
|---|---|
jwt.sign |
Creates token |
jwt.verify |
Validates token |
token |
Signed data |
secret |
Secret key |
3 What does JWT provide?
- File compression
- Network acceleration
- Stateless authentication Correct answer
- A database connection
Explanation: JWT provides stateless authentication.