From 1f4a835a65f0ed52f3580329db48f766afa0080c Mon Sep 17 00:00:00 2001 From: KamyarTaher <61198701+KamyarTaher@users.noreply.github.com> Date: Sat, 9 Nov 2024 00:28:10 +0100 Subject: [PATCH] p --- src/app/backendAPI/tokenFetch.ts | 10 ++++------ src/pages/api/set-cookie.ts | 20 ++++++++++++++++++-- 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/src/app/backendAPI/tokenFetch.ts b/src/app/backendAPI/tokenFetch.ts index 71da661..31df9e0 100644 --- a/src/app/backendAPI/tokenFetch.ts +++ b/src/app/backendAPI/tokenFetch.ts @@ -1,12 +1,10 @@ export async function fetchToken(reconnect: boolean): Promise { try { - const response = await fetch( - `https://play.metacube.games/api/set-cookie?reconnect=${reconnect}`, - { + const response = // Client-side call + await fetch("/api/set-cookie?reconnect=true", { method: "GET", - credentials: "include", // Ensures cookies are included - } - ); + credentials: "include", + }); if (!response.ok) { // Handle specific HTTP error status if needed diff --git a/src/pages/api/set-cookie.ts b/src/pages/api/set-cookie.ts index d14a460..9bf6d89 100644 --- a/src/pages/api/set-cookie.ts +++ b/src/pages/api/set-cookie.ts @@ -8,9 +8,25 @@ export default async function handler( req: NextApiRequest, res: NextApiResponse ) { + // Allow credentials and specific origin for cookies to be set + res.setHeader( + "Access-Control-Allow-Origin", + "https://your-frontend-domain.com" + ); + res.setHeader("Access-Control-Allow-Credentials", "true"); + + 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"); + res.status(200).end(); + return; + } + try { const reconnect = req.query.reconnect || "false"; + // Continue with the token fetching and cookie setting as before const backendResponse = await axios.get(`${BASE_URL}auth/refresh`, { params: { reconnect }, withCredentials: true, @@ -28,8 +44,8 @@ export default async function handler( "Set-Cookie", cookie.serialize("userToken", token, { httpOnly: true, - secure: true, // Ensure secure in production - sameSite: "none", // Set to 'none' if cross-origin + secure: process.env.NODE_ENV === "production", + sameSite: "none", // Cross-site cookie setting path: "/", }) );