Token Creation in Practice In order to create tokens, we'll make use of the jsonwebtoken package. We'll need to import it inside of our project: // controllers/users.js const jwt = require('jsonwebtoken'); // importing the jsonwebtoken module Afterwards, we can call the jwt.sign() method to create a token: // controllers/users.js const jwt = require('jsonwebtoken'); module.exports.login = (req, res) => { const { email, password } = req.body; return User.findUserByCredentials(email, password) .then((user) => { // we're creating a token const token = jwt.sign({ _id: user._id }, 'some-secret-key'); // we return the token res.send({ token }); }) .catch((err) => { res .status(401) .send({ message: err.message }); }); }; We pass two arguments to the sign() method: the token's payload and the secret key for the signature: const token = jwt.sign({ _id: user._id }, 'some-secret-key'); The token's payload is an encrypted user object. We can send as much information as we'd like to be encrypted; however, we recommend that you avoid creating excess traffic and only encrypt the most pertinent information. In this case, it's enough to encrypt the user's unique ID. The sign() method also has an optional third parameter, an options object. You can check out the full list of options available with this object inside the official jsonwebtoken documentation. We're really only interested in one of these options, expiresIn. This is a length of time that specifies how long a token will be valid. We can pass a number here, which the sign() method will recognize as a number of seconds: const token = jwt.sign( { _id: user._id }, 'some-secret-key', { expiresIn: 3600 } // this token will expire an hour after creation ); We can pass a string argument containing numbers and letters. The letters will indicate the unit of measurement, milliseconds, minutes, hours, or days: expiresIn: '120ms' // 120 miliseconds expiresIn: '15m' // 15 minutes expiresIn: '2h' // 2 hours expiresIn: '7d' // 7 days Should we choose to pass nothing to expiresIn, the token will never expire.
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter