Node.js Authentication with JWT and Refresh TokensNode.js / Backend

Node.js Authentication with JWT and Refresh Tokens

By Jeevan BhargavJun 13, 20261 min read22 Views

Featured Learning Resources

Boost your interview confidence. Practice coding layouts, review real-time feedback, and optimize your resume structure.

All Questions

Node.js Authentication with JWT and Refresh Tokens

JWT authentication is the industry standard for stateless APIs. Here's how to implement it properly with refresh tokens.


Login and Token Generation

import jwt from 'jsonwebtoken';

async function login(email: string, password: string) {
  const user = await db.user.findUnique({ where: { email } });
  const valid = await bcrypt.compare(password, user.password);
  if (!valid) throw new Error('Invalid credentials');

  const accessToken = jwt.sign({ userId: user.id }, process.env.JWT_SECRET!, { expiresIn: '15m' });
  const refreshToken = jwt.sign({ userId: user.id }, process.env.REFRESH_SECRET!, { expiresIn: '7d' });

  return { accessToken, refreshToken };
}

Refresh Token Route

router.post('/refresh', (req, res) => {
  const { refreshToken } = req.body;
  const payload = jwt.verify(refreshToken, process.env.REFRESH_SECRET!) as any;
  const accessToken = jwt.sign({ userId: payload.userId }, process.env.JWT_SECRET!, { expiresIn: '15m' });
  res.json({ accessToken });
});

Final Thoughts

Short-lived access tokens + long-lived refresh tokens is the safest JWT pattern. Always store refresh tokens in httpOnly cookies.

Happy Coding!

Share this Resource

Spread the knowledge with other engineering candidates.

Was this card helpful?

Help us rank high-quality interview preparation materials.

Jeevan Bhargav

Written by Jeevan Bhargav

Creator of InterviewsAce.AI and Frontend Engineer.

Discussion (0)

Please log in to participate in technical discussions.

No comments yet. Start the discussion!