Login and Tokens
A login token is a small signed record that proves a login. The server signs it and hands it to the frontend after a good login.
Signing a token
sign builds a token from a small payload.
const token = jwt.sign({ username: 'ana' }, 'dev-secret');Reading a token
verify checks the signature and returns the payload.
const token = jwt.sign({ username: 'ana' }, 'dev-secret');
const payload = jwt.verify(token, 'dev-secret');
console.log(payload.username);Example
import jwt from 'jsonwebtoken';
const secret = 'dev-secret';
const token = jwt.sign({ username: 'ana' }, secret, { expiresIn: '1h' });
const decoded = jwt.verify(token, secret);
console.log(decoded.username);
console.log(typeof token === 'string');Key points
- A JWT is a JSON Web Token, a signed record of a login.
- The server signs the token with a secret key.
- The token carries the username and an expiry time.
- The frontend sends the token with each later request.
- A token with a changed signature is rejected.
In this example, the script signs a token for one user. It then checks the token with the same secret. The printed name comes from the decoded payload. The token itself is never printed.
Note
The token is proof of login, not a password.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does the server check when it reads a token?