-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.js
32 lines (26 loc) · 1.08 KB
/
middleware.js
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
import { NextResponse } from 'next/server';
// Authentication middleware
export async function middleware(request) {
// if the token is present in the cookies
let hasJWT = request.cookies.has('jwt');
if (hasJWT) {
// get the token from cookies
let jwtCookie = request.cookies.get('jwt').value;
// check if user is authenticated
const options = {
method: 'GET',
headers: { 'Authorization': `Bearer ${jwtCookie}` }
}
const response = await fetch(process.env.NEXT_PUBLIC_API_URL + "/user/me", options);
// redirect to login page if user is not authenticated
if (response.status !== 200) return NextResponse.redirect(new URL('/auth/signIn', request.url));
// allow access to authenticated users
else return NextResponse.next();
}
// no token, redirect to login page
return NextResponse.redirect(new URL('/auth/signIn', request.url));
}
// middleware is applied to the following routes
export const config = {
matcher: ['/cart', '/delivery', '/delivery/:id', '/profile'],
}