9

I have two VERCEL servers running. One is for server and second for client.

Server is running NODE -> express -> express-sessions.

Client is running Svelte with fetch api.

My server is setting cookies right and sending them but my browser is not saving the cookies.

My vercel.json is:

{
  "src": "/api/login",
  "dest": "/api/index.js",
  "headers": {
    "Access-Control-Allow-Origin": "{mydomain}",
    "Access-Control-Allow-Methods": "GET,OPTIONS,PATCH,DELETE,POST,PUT",
    "Access-Control-Allow-Headers": "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version",
    "Access-Control-Allow-Credentials": "true"
  },
  "continue": true
},

The express app is:

app.set('trust proxy', 1);
app.use(cookieParser("secretcode"));
app.use(session({
    secret: "secretcode",
    resave: true,
    saveUninitialized: true,
    cookie: {
        maxAge: 60000 * 10,
        secure: true
    },
    store: new MongoStore({ mongooseConnection: mongoose.connection })
}))
app.use(passport.initialize());
app.use(passport.session());

The login endpoint is:

const login = async (req, res, next) => {
  passport.authenticate("local", (err, user, info) => {
    if (err) throw err;
    if (!user) {
      res.status(200)
      res.send("No User Exists")
    } else {
      req.logIn(user, (err) => {
        if (err) throw err;
        res.status(200)
        req.session.user = user;
        res.send({
          "message": "Successfully logged in"
        });
      });
    }
  })(req, res, next)
}

The client code is:

async function login() {
    await fetch("{mydomain}/api/login", {
      method: "post",
      credentials: 'include',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        username: username,
        password: password
      })
    })
  }

What I have tried:

  1. Changing vercel.json Access-Control-Allow-Origin to *

  2. Adding/removing credentials: 'include'

nothing is working.

There is two requests: enter image description here

This is the req and respons headers: enter image description here

And this are the cookies: enter image description here

I do run everything from https, I have even tried only http with no luck. Also in insomnia, it works flawleslly.

Lumca
  • 163
  • 8

0 Answers0