From 955f5f89de04fcdfd8a46c0528c1a99a615a6a12 Mon Sep 17 00:00:00 2001 From: KamyarTaher <61198701+KamyarTaher@users.noreply.github.com> Date: Sat, 9 Nov 2024 01:07:02 +0100 Subject: [PATCH] p --- src/pages/api/set-cookie.ts | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/src/pages/api/set-cookie.ts b/src/pages/api/set-cookie.ts index f183292..8df619a 100644 --- a/src/pages/api/set-cookie.ts +++ b/src/pages/api/set-cookie.ts @@ -15,10 +15,10 @@ export default async function handler( res: NextApiResponse ) { // Allow credentials and specific origin for cookies to be set - res.setHeader("Access-Control-Allow-Origin", "https://play.metacube.games"); // Ensure no trailing slash + res.setHeader("Access-Control-Allow-Origin", "https://play.metacube.games"); res.setHeader("Access-Control-Allow-Credentials", "true"); - if (req.method === "OPTIONS") { + if (req?.method === "OPTIONS") { // Handle CORS preflight request res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); res.setHeader("Access-Control-Allow-Headers", "Content-Type"); @@ -27,18 +27,26 @@ export default async function handler( } try { - const reconnect = req.query.reconnect || "false"; + const reconnect = req?.query?.reconnect || "false"; + + // Extract cookies from the incoming request + const cookies = req.headers?.cookie || ""; // Attempt to fetch the token from backend const backendResponse = await api.get("auth/refresh", { - params: { reconnect: reconnect.toString() }, + params: { reconnect: reconnect?.toString() }, withCredentials: true, + headers: { + // Forward the cookies to the backend + Cookie: cookies, + }, }); + // Check if the backend response status is successful - if (backendResponse.status !== 200) { + if (backendResponse?.status !== 200) { console.error( "Error: Non-200 response from backend:", - backendResponse.status + backendResponse?.status ); return res .status(backendResponse.status) @@ -50,7 +58,7 @@ export default async function handler( if (!token) { console.error( "Error: Token missing in backend response:", - backendResponse.data + backendResponse?.data ); return res.status(500).json({ error: "Token not found in response" }); } @@ -59,7 +67,7 @@ export default async function handler( "Set-Cookie", cookie.serialize("userToken", token, { httpOnly: true, - secure: true, // Only use Secure in production + secure: true, // Use secure only in production sameSite: "none", // Cross-site cookie setting path: "/", })