How to get express-session cookie on frontend in production with Railway express backend and Railway CRA frontend?

34 views Asked by At

I have a create-react-app frontend and an expressjs backend api using express session cookies for session management. My application runs perfectly on localhost including the cookies being saved properly in the frontend. I deployed both frontend and backend to Railway, and they both work mostly. Logging in works with a successful 200 code, meaning that my frontend is able to interact with my backend's MongoDB database just fine. The only problem is that my cookie won't save on production like it does on localhost. I've tried many combinations of express session cookie properties, but I feel like I am missing something. Please help!

Server CORS/Cookie Code

app.use(cors({
    origin: ["http://localhost:3000", "https://operazzi-production.up.railway.app"],
    credentials: true,
}));
app.use(
    session({
      secret: env.SESSION_SECRET,
      resave: false,
      saveUninitialized: false,
      cookie: {
        httpOnly: true,
        secure: true,
        maxAge: 60 * 60 * 1000,
        sameSite: "none",
      },
      rolling: true,
      store: MongoStore.create({
        mongoUrl: env.MONGO_CONNECTION_STRING,
      }),
    })
  );

Frontend API Call

async function fetchData(input: RequestInfo, init?: RequestInit) {
  init = {...init, credentials: 'include'};
  const response = await fetch(`${apiUrl}${input}`, init);
  if (response.ok) {
    return response;
  } else {
    const errorBody = await response.json();
    const errorMessage = errorBody.error;
    if (response.status === 401) {
      throw new UnauthorizedError(errorMessage);
    } else if (response.status === 409) {
      throw new ConflictError(errorMessage);
    } else {
      throw Error(
        "Request failed with status: " +
          response.status +
          " message: " +
          errorMessage
      );
    }
  }
}

I can provide more code, if needed for context. Thanks!

0

There are 0 answers