-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
44 lines (36 loc) · 1.12 KB
/
middleware.ts
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
42
43
44
import supabase from '@/lib/supabase';
import { NextResponse } from 'next/server';
export const config = {
matcher: ['/api/trips/:function*', '/api/flights/:function*', '/api/stays/:function*'],
};
export async function middleware(req: NextResponse) {
const authHeader: string = req.headers.get('authorization') || '';
const token: string = authHeader ? authHeader.split('Bearer ')[1] : '';
try {
if (!token) throw new Error();
// Check if token returns valid user
const { user, error } = await supabase.auth.api.getUser(token);
if (error) throw error;
// Clone the request headers and set a new user header
const requestHeaders = new Headers(req.headers)
requestHeaders.set('userid', user?.id || '')
const res = NextResponse.next({
request: {
// New request headers
headers: requestHeaders,
},
})
return res;
} catch (error) {
return new NextResponse(
JSON.stringify({
statusCode: 401,
statusMessage: 'Invalid token',
}),
{
status: 401,
headers: { 'content-type': 'application/json' }
}
)
}
}