Handle Token Refresh

You can use refresh tokens to get new access tokens when they expire.

Access tokens normally have short expiration windows, so you'll want to use the refresh token to get new access tokens for users in your Express server.


Refresh Tokens in Auth Middleware

Use the Wristband SDK in your auth middleware to call the refreshTokenIfExpired() function.

import wristbandAuth from './wristband-auth';

// Middleware that ensures there is an authenticated user session and JWTs are present.
const authMiddleware = async function (req, res, next) {
  const { expiresAt, isAuthenticated, refreshToken } = req.session;
  if (!isAuthenticated) {
    return res.status(401).send();
  }
  
  /* ***** BEGIN TOKEN REFRESH LOGIC ***** */

  try {
    // If no refresh was needed yet, null is returned from the function.
    const tokenData = await wristbandAuth.refreshTokenIfExpired(refreshToken, expiresAt);
    if (tokenData) {
      req.session.accessToken = tokenData.accessToken;
      req.session.expiresAt = Date.now() + tokenData.expiresIn * 1000;
      req.session.refreshToken = tokenData.refreshToken;
    }

    // Save the session in order to "touch" it (even if there is no new token data) to extend the session expiration window.
    await req.session.save();
    return next();
  } catch (error) {
    console.error(`Failed to refresh token due to: ${error}`);
    return res.status(401).send();
  }
  
  /* ***** END TOKEN REFRESH LOGIC ***** */
};

export default authMiddleware;


Let's make sure the token refresh mechanism is working.