How to set an active session after registration


I’m trying to set the ‘/register’ handle in my app.js file and it seems to not keep the user logged in after registration is complete.

This is the handle:

// Register new user'/register', async (req, res) => {
  try {
      console.log('Received registration request:', req.body);

      const { username, email, password } = req.body;

      const existingUser = await User.findOne({ email });

      if (existingUser) {
          console.log('Email already registered:', email);
          return res.status(400).json({ success: false, error: 'Email already registered' });

      const newUser = new User({


      console.log('User registered successfully:', newUser);

      req.session.user = {
          userId: newUser._id.toString(),
          username: newUser.username,

      res.status(200).json({ success: true, user: req.session.user });

  } catch (error) {
      console.error('Error processing user registration:', error);
      res.status(500).json({ success: false, error: error.message, stack: error.stack });

Obviously I’m using express and express-session, and also ejs, mongoose and cookie-parser.

So with this code the user isn’t logged in at the end of the registration. Somebody know why it won’t keep the user logged in?