This repository has no description
1import { GetProfileResponse } from '@/api-client/ApiClient';
2import { cookies } from 'next/headers';
3import { redirect } from 'next/navigation';
4import { cache } from 'react';
5
6const appUrl = process.env.NEXT_PUBLIC_APP_URL || 'http://127.0.0.1:4000';
7
8interface Options {
9 redirectOnFail?: boolean;
10}
11
12export const verifySessionOnServer = cache(async (options?: Options) => {
13 const cookieStore = await cookies();
14 const accessToken = cookieStore.get('accessToken')?.value;
15 const refreshToken = cookieStore.get('refreshToken')?.value;
16
17 // tokens are missing
18 if (!accessToken || !refreshToken) {
19 if (options?.redirectOnFail) {
20 redirect('/login');
21 }
22 return null;
23 }
24
25 const res = await fetch(`${appUrl}/api/auth/me`, {
26 headers: {
27 Cookie: cookieStore.toString(), // forward user's cookies
28 },
29 });
30
31 if (!res.ok) {
32 if (options?.redirectOnFail) {
33 redirect('/login');
34 }
35 return null;
36 }
37
38 const { user }: { user: GetProfileResponse } = await res.json();
39
40 return user;
41});