Session NOT persisting Redis-Server in React App

I created a react app that works with the spotify API. Within it, I am setting up a backend to handle my Spotify auth using a redis-server. It seems to be working fine except for when I set up this middleware to check access tokens in which it checks the session for an existing access token.

Every time it checks the session contains no variables although they do get properly set after the token is generated. I am not sure if I am understanding sessions correctly or if there is an issue with my code, but essentially, I’d like for the middleware to work when using other endpoints to persist the access token across the backend.

Here is my code for reference:

Redis set up

app.use(session({
  store: new RedisStore({ client: redisClient }),
  secret: process.env.SESSION_SECRET || 'fallback_default_secret_key',
  resave: false,
  saveUninitialized: true,
  cookie: {
    secure: process.env.NODE_ENV === 'production', // Ensure cookies are only sent over HTTPS in production
    httpOnly: true, // Prevent client-side JavaScript from accessing the cookie
    maxAge: 3600000 // Optional: Set a 1-hour expiration for cookies
  }
}));

Middleware to refresh token if expired, currently not working as session data is not persisting:

const checkAccessToken = async (req, res, next) => {
  console.log('Session data:', req.session); // Log the session object to verify

  let accessToken = req.session.accessToken;
  const refreshToken = req.session.refreshToken;
  const tokenExpiresIn = req.session.tokenExpiresIn;

  if (!accessToken || Date.now() >= tokenExpiresIn) {
    try {
      // Use the refresh token to get a new access token
      const authString = `${process.env.CLIENT_ID}:${process.env.CLIENT_SECRET}`;
      const base64Auth = Buffer.from(authString).toString('base64');

      const response = await axios.post('https://accounts.spotify.com/api/token',
        new URLSearchParams({
          grant_type: 'refresh_token',
          refresh_token: refreshToken
        }).toString(), {
          headers: {
            'Authorization': 'Basic ' + base64Auth,
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        });

      // Update session with new access token and expiration time
      accessToken = response.data.access_token;
      req.session.accessToken = accessToken;
      req.session.tokenExpiresIn = Date.now() + response.data.expires_in * 1000;

      req.accessToken = accessToken;
      next(); // Proceed to the next middleware

    } catch (error) {
      console.error('Error refreshing access token:', error.response ? error.response.data : error.message);
      return res.status(500).json({ error: 'Failed to refresh access token. Please re-authenticate.' });
    }
  } else {
    req.accessToken = accessToken;
    next();
  }
};

Setting access token to session:

router.post('/token', async (req, res) => {
  const { code, codeVerifier } = req.body;

  try {
    const authString = `${clientId}:${clientSecret}`;
    const base64Auth = Buffer.from(authString).toString('base64');

    const response = await axios.post('https://accounts.spotify.com/api/token', 
      new URLSearchParams({
        grant_type: 'authorization_code',
        code,
        redirect_uri: redirectUri,
        code_verifier: codeVerifier
      }).toString(), {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': 'Basic ' + base64Auth
      }
    });
    const { access_token, refresh_token, expires_in } = response.data;
    req.session.accessToken = access_token;
    req.session.refreshToken = refresh_token;
    req.session.tokenExpiresIn = Date.now() + expires_in * 1000;

    res.json({ message: 'Token generated successfully' });
  } catch (error) {
    console.error('Error exchanging code for token:', error.response ? error.response.data : error.message);
    res.status(500).json({ error: 'Failed to exchange code for token' });
  }
});

// Callback route to handle redirect from Spotify
router.get('/callback', (req, res) => {
    const code = req.query.code;
    const state = req.query.state;
    res.redirect(`http://localhost:5173/callback?code=${code}&state=${state}`);
});