1

I am using two Next.js projects,

  • The first one is a Login platform on localhost:3000 where user can create their account an access information.
  • The second one on localhost:3001 is the Website

The Website is using a custom Next route /pages/api/login that fetch the login endpoint of the Login platform which is also a custom Next API Route /pages/api/get-connected-user.

When a user is connected from the Login Platform, a Server Cookie is set. If this cookie is available, the api check if the user is connected an will return "true". When I directly call the /pages/api/login I can get the true value but once I am calling it from the Website API (which call the same endpoint) it always return false since the cookies are not available inside req.headers since cookie are not passed

/pages/api/login

import axios from 'axios'
import { NextApiResponse } from 'next'

export default async (req: any, res: NextApiResponse) => {
  const domain = 'http://localhost:3001/'

  try {
    const url = `http://localhost:3000/api/get-connected-user`

    const { data } = await axios.get(url, { withCredentials: true })
    res.send(JSON.stringify(data))
   }
   

/pages/api/get-connected-user

import { NextApiResponse } from "next";
import { getUserFromServer } from "api/user";

export default async (req: any, res: NextApiResponse) => {
  const { ref } = req.query;

  try {
    const isConnected = (req.headers?.cookie?.toString() || "").includes(
      "isConnected=true"
    );

    console.log(req.headers?.cookie?.toString());

    const serverCookie = req.headers?.cookieuser;
    let user;
    if (!isConnected && serverCookie)
      user = await getUserFromServer(serverCookie);
    const response = isConnected || !!user?.id;

    res.send(JSON.stringify({ isConnected: response }));
  } catch (err) {
    res.send(JSON.stringify(err));
  }
};

My conclusion is by hitting /pages/api/login is it does not send the cookie from my req through the distant endpoint which I know is for security reason but I am asking myself if it exist a way to do it ?

Dupflo
  • 305
  • 3
  • 7
  • 1
    Does this answer your question: [Why are cookies not sent to the server via getServerSideProps in Next.js?](https://stackoverflow.com/a/69058105/1870780) (mentions `getServerSideProps` but same applies to API routes)? You need to explicitly pass the cookies to the axios request in `/pages/api/login`. – juliomalves Jan 25 '22 at 18:44

0 Answers0