Skip to content

Commit

Permalink
p
Browse files Browse the repository at this point in the history
  • Loading branch information
KamyarTaher committed Nov 8, 2024
1 parent a3822a7 commit 1f4a835
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 8 deletions.
10 changes: 4 additions & 6 deletions src/app/backendAPI/tokenFetch.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
export async function fetchToken(reconnect: boolean): Promise<string> {
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
Expand Down
20 changes: 18 additions & 2 deletions src/pages/api/set-cookie.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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: "/",
})
);
Expand Down

0 comments on commit 1f4a835

Please sign in to comment.