File size: 1,269 Bytes
eaab0a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import { NextRequest, NextResponse } from 'next/server';
import { withDb } from '@/lib/api-handler';
import { getCookieToken, deleteSession, SESSION_COOKIE_NAME } from '@/lib/auth';

async function handler(request: NextRequest) {
  try {
    const token = getCookieToken(request);

    if (token) {
      await deleteSession(token);
    }

    // ── Determine if behind HTTPS proxy ───────────────────────────────
    const forwardedProto = request.headers.get('x-forwarded-proto');
    const isSecure = forwardedProto === 'https' || process.env.NODE_ENV === 'production';

    const response = NextResponse.json({ success: true });

    const host = request.headers.get('host') || '';
    const domain = host.includes('localhost') ? undefined : `.${host.split(':')[0]}`;

    response.cookies.set(SESSION_COOKIE_NAME, '', {
      httpOnly: true,
      secure: isSecure,
      sameSite: 'lax',
      path: '/',
      maxAge: 0,
      ...(domain ? { domain } : {}),
    });

    return response;
  } catch (error) {
    console.error('[LOGOUT_ERROR]', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}

export const POST = withDb(handler);