Skip to content

Commit

Permalink
p
Browse files Browse the repository at this point in the history
  • Loading branch information
KamyarTaher committed Nov 9, 2024
1 parent cd89370 commit 955f5f8
Showing 1 changed file with 16 additions and 8 deletions.
24 changes: 16 additions & 8 deletions src/pages/api/set-cookie.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand All @@ -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)
Expand All @@ -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" });
}
Expand All @@ -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: "/",
})
Expand Down

0 comments on commit 955f5f8

Please sign in to comment.