How to send Cookies to subsequent API request to a particular domain in NextJS

32 views Asked by At

This is my code for Login API which returns two cookies 1) Authentication 2) Refresh tokens with path and max-Age and I am storing it into browser cookies.Browser is storing cookies with max-Age and path but showing domain='localhost'.

import { NextApiRequest, NextApiResponse } from "next";
import Url from "./API";
import { Domain } from "domain";

export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method === "POST") {
const { email, password } = req.body;
try {
  const apiResponse = await fetch(Url.LOGIN_STUDENT(), {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      email: email,
      password: password,
    }),
  });

  if (apiResponse.ok) {
    let responseData = await apiResponse.json();
    const cookie = apiResponse.headers.get("Set-Cookie");
    if (cookie) {
      res.setHeader("Set-Cookie", cookie);
    }
    res.status(200).json({ success: true, data: responseData });
  } else {
    const errorData = await apiResponse.json();
    res
      .status(apiResponse.status)
      .json({ success: false, error: errorData });
  }
} catch (error) {
  console.error(error);
  res.status(500).json({ success: false, error: "Internal Server Error" });
}
} else {
res.status(405).end();
}
}

This is my code for Logout API which requires both of cookies to be included in request.Now how to achieve this automatically?

import { NextApiRequest, NextApiResponse } from 'next';
import Url from './API';


export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method === 'POST') {
const { email } = req.body;
const cookieFromRequest = req.headers.cookie;
console.log(cookieFromRequest)
try {
  const apiResponse = await fetch(Url.LOGOUT_STUDENT(), {
    method: 'POST',
    credentials: 'include',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      email: email,
    }),
  });
  console.log('api response : ', apiResponse);
  console.log(apiResponse.headers.get('Cookie'))
  if (apiResponse.ok) {
    let responseData = await apiResponse.json();
    const cookie = apiResponse.headers.get('Set-Cookie');
    if(cookie){
    res.setHeader("Set-Cookie", cookie)
    }
    res.status(200).json({ success: true, data: responseData });
  } else {
    const errorData = await apiResponse.json();
    res.status(apiResponse.status).json({ success: false, error: errorData });
  }
} catch (error) {
  console.error(error);
  res.status(500).json({ success: false, error: 'Internal Server' });
}
} else {
res.status(405).end();
}
}

Here is the actual endpoints for both API :

const LIVE_URL = 'https://api-68jp.onrender.com';

const Url = {

/* Register endpoint */

REGISTER_STUDENT : () => `${LIVE_URL}/authentication/student/register`,

/* Login endpoint */

LOGIN_STUDENT : () => `${LIVE_URL}/authentication/student/log-in`,

/* Logout endpoint */

LOGOUT_STUDENT :() => `${LIVE_URL}/authentication/student/log-out`
}
export default Url;
0

There are 0 answers