skip to Main Content

I’m using Next JS as a client.

Using the js-cookie library I am setting a cookie called FarmId: Cookies.set(‘FarmId’, farmId)

In my axios.create I am already setting the withCredentials property to true:

const axiosClient = axios.create({
  withCredentials: true,
  baseURL: apiUrl,
  headers: {
    Authorization: 'Bearer ' + token,
  },
})

However, my problem is that when I make the request to the API, the Cookie is not being sent

const response = await api.get<IFarm[]>('/api/Farms')

(https://phpout.com/wp-content/uploads/2023/12/ekra6.png)

Through Postman, it is sending normally, I also tested it by creating a NodeJS application and it worked normally too.

I’m trying to figure out how to send the cookies to the API and hope to find a solution that will help me resolve this issue

2

Answers


  1. When working with cookies and Next.js, there are a few things to consider to ensure that cookies are sent correctly with your requests:

    1. Credentials in CORS (Cross-Origin Resource Sharing):
      If your API is hosted on a different domain from your Next.js application, you need to ensure that the server allows credentials (including cookies) from your domain. This is a CORS-related issue.

      On the server (where your API is hosted), make sure that the CORS middleware is configured to allow credentials. In your API server code, you might have something like:

      app.use(cors({ credentials: true, origin: 'http://your-nextjs-app.com' }));
      

      Replace 'http://your-nextjs-app.com' with the actual origin of your Next.js application.

    2. Set Cookies with SameSite=None and Secure (for cross-site cookies):
      If your API and Next.js application are on different domains, and you are dealing with cross-site cookies, you need to set the SameSite=None attribute and use Secure if your application is served over HTTPS.

      Cookies.set('FarmId', farmId, { sameSite: 'None', secure: true });
      

      This ensures that the cookie is sent with cross-site requests.

    3. Verify Axios Configuration:
      Double-check your Axios configuration to ensure that withCredentials: true is set globally for your Axios instance.

      const api = axios.create({
        withCredentials: true,
        baseURL: apiUrl,
        headers: {
          Authorization: 'Bearer ' + token,
        },
      });
      

      Make sure that this instance is used consistently throughout your application.

    4. Test Locally and Check Network Tab:
      Test your application locally and check the network tab in your browser’s developer tools. Look at the request headers and see if the Cookie header is present and contains the expected values.

      Also, check the response headers to see if the server is setting any cookies.

      This can help you identify whether the issue is on the client side or the server side.

    5. Ensure Secure and HTTPOnly Cookies:
      Check if the cookies are set with the Secure and HttpOnly flags. This is especially important for session cookies.

      Cookies.set('FarmId', farmId, { secure: true, httpOnly: true });
      

    By addressing these points and ensuring that your server allows credentials and your cookies are set appropriately, you should be able to send cookies successfully from your Next.js application to your API. If the issue persists, further debugging with the network tab and checking the server logs might provide additional insights.

    Login or Signup to reply.
  2. Additional be careful in nextjs server-side and client-side cookies set is diffrence:
    In Next.js, cookies can be set in both server-side components and client-side components, but there are differences in how you handle cookies on the server side compared to the client side.

    Server-Side Components (Pages in the pages/api directory):

    In server-side components, such as those in the pages/api directory, you can set cookies using the setHeader method of the response object. Here’s an example:

    // pages/api/example.js
    
    export default function handler(req, res) {
      // Your logic to determine the cookie value
      const farmId = 'someFarmId';
    
      // Set the cookie in the response header
      res.setHeader('Set-Cookie', `FarmId=${farmId}; Path=/; HttpOnly; Secure; SameSite=None`);
    
      // Your API logic here
    
      // Send the response
      res.status(200).json({ success: true });
    }
    

    Make sure to adjust the farmId and cookie attributes based on your requirements.

    Client-Side Components:

    In client-side components, you can use client-side libraries like js-cookie or the native document.cookie API to set cookies. Here’s an example using js-cookie:

    // Import the library
    import Cookies from 'js-cookie';
    
    // Your component logic
    const setCookieHandler = () => {
      // Your logic to determine the cookie value
      const farmId = 'someFarmId';
    
      // Set the cookie using js-cookie
      Cookies.set('FarmId', farmId, { secure: true, httpOnly: true, sameSite: 'None' });
    
      // Your component logic here
    };
    

    Again, adjust the farmId and cookie attributes based on your requirements.

    Important Considerations:

    1. Security Considerations:

      • On the server side, you should set the HttpOnly flag for increased security.
      • For client-side cookies, be cautious about setting sensitive data in cookies, as they are visible and modifiable by the client.
    2. SameSite and Secure Flags:

      • For cross-site cookies, set SameSite=None and use Secure if your application is served over HTTPS.
    3. Handling on the Client Side:

      • If you set a cookie on the server side, you won’t immediately see it on the client side. The client-side JavaScript will only be able to access and modify cookies after a subsequent request/response cycle.
    4. Consistency:

      • Ensure consistency in how you handle cookies across your application. Use a single approach (server-side or client-side) for a given cookie.

    By following these considerations, you can set and manage cookies effectively in both server-side and client-side components in your Next.js application.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search