MyInternships.in

Authentication & Security

Node.js Refresh Tokens

A refresh token is a long-lived credential stored server-side that issues new short-lived access tokens. It gives the convenience of staying logged in with the ability to revoke access immediately.


What is Refresh Tokens in Node.js?

A refresh token is a long-lived credential stored server-side that issues new short-lived access tokens. It gives the convenience of staying logged in with the ability to revoke access immediately.

Refresh Tokens example

Rotating refresh tokens
JavaScript
// login: short access token + long refresh token stored in the database
const accessToken  = jwt.sign({ sub: user.id }, ACCESS_SECRET,  { expiresIn: '15m' });
const refreshToken = crypto.randomBytes(40).toString('hex');

await RefreshToken.create({
  token: await bcrypt.hash(refreshToken, 10),   // store hashed
  userId: user.id,
  expiresAt: new Date(Date.now() + 30 * 24 * 3600 * 1000),
});

// refresh endpoint: verify, then ROTATE
app.post('/api/auth/refresh', async (req, res) => {
  const record = await findValidRefreshToken(req.cookies.refresh);
  if (!record) return res.status(401).json({ error: 'Invalid refresh token' });

  await RefreshToken.deleteOne({ _id: record._id });   // single use
  // issue a new pair…
});

Key points to remember

  • Rotate on every use — a reused token indicates theft and should revoke the whole family.
  • Store refresh tokens hashed, exactly like passwords.
  • Logout deletes the stored refresh token, which genuinely ends the session.

Common mistakes with Refresh Tokens

  • Storing refresh tokens in plain text, so a database leak grants permanent access.
  • Never expiring refresh tokens.

Node.js Refresh Tokens— Interview Questions & FAQs

Why use both an access token and a refresh token?+

The access token is short-lived so a stolen one is useless quickly, while the refresh token lives server-side and can be revoked. Together they give both security and a session that does not expire every fifteen minutes.

Related Node.js Topics

Keep learning with these closely related lessons.

Ready to use your Node.js skills?

Find verified Node.js internships and fresher developer jobs across India.

Browse Node.js Internships