-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmiddleware.ts
More file actions
35 lines (25 loc) · 1.04 KB
/
middleware.ts
File metadata and controls
35 lines (25 loc) · 1.04 KB
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
import { NextResponse } from 'next/server';
import ROUTE_PATHS from './constants/route';
import { decodeJWT } from './utils/decodeJWT';
import type { NextRequest } from 'next/server';
export async function middleware(request: NextRequest) {
const token = request.cookies.get('accessToken');
if (!token) {
return NextResponse.redirect(new URL(ROUTE_PATHS.SIGN_IN, request.url));
}
const decodedPayload = decodeJWT(token.value);
const response = await fetch(`${process.env.NEXT_PUBLIC_BASE_API_URL}/users/${decodedPayload.userId}`);
const {
item: { type },
} = await response.json();
if (type === 'employee' && request.nextUrl.pathname.startsWith(ROUTE_PATHS.STORE)) {
return NextResponse.redirect(new URL(ROUTE_PATHS.PROFILE, request.url));
}
if (type === 'employer' && request.nextUrl.pathname.startsWith(ROUTE_PATHS.PROFILE)) {
return NextResponse.redirect(new URL(ROUTE_PATHS.STORE, request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ['/my-store/:path*', '/my-profile/:path*'],
};