Files
ember-market-frontend/app/api/auth/set-cookie/route.ts
NotII 3413e3b1e8 ugh
2025-03-23 23:53:45 +00:00

59 lines
1.8 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server';
// Force dynamic execution to ensure cookies are set at runtime
export const dynamic = 'force-dynamic';
export async function POST(req: NextRequest) {
try {
// Parse the request body to get the auth token
const body = await req.json();
const { token } = body;
if (!token) {
console.error('Set-cookie API: No token provided');
return NextResponse.json(
{ error: 'No token provided' },
{ status: 400 }
);
}
// Create a response object
const response = NextResponse.json(
{ success: true },
{ status: 200 }
);
// Set the token in an HTTP-only cookie that will be sent with requests
// The secure flag is conditionally set based on the environment
const isLocalhost = req.headers.get('host')?.includes('localhost') ||
req.headers.get('host')?.includes('127.0.0.1');
const cookieOptions = {
// HttpOnly for security - prevents JavaScript access
httpOnly: true,
// Valid for 7 days (same as the JWT)
maxAge: 7 * 24 * 60 * 60,
// Only send in requests to our domain
path: '/',
// Strict same-site policy to prevent CSRF
sameSite: 'strict' as const,
// Secure only in production environments
secure: !isLocalhost
};
// Set the cookie with the options
response.cookies.set('Authorization', token, cookieOptions);
console.log('Set-cookie API: Cookie set successfully');
return response;
} catch (error) {
console.error('Set-cookie API error:', error);
return NextResponse.json(
{
error: 'Failed to set cookie',
details: error instanceof Error ? error.message : String(error)
},
{ status: 500 }
);
}
}