-
Notifications
You must be signed in to change notification settings - Fork 1
/
middleware.ts
75 lines (63 loc) · 2.1 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import Negotiator from 'negotiator';
import { NextRequest, NextResponse } from 'next/server';
import { getSupportedLocales } from './locale';
const locales = getSupportedLocales();
function getLocale(request: Request) {
return new Negotiator({
headers: Object.fromEntries(request.headers.entries()),
}).language(locales) ?? 'ko';
}
export function middleware(request: NextRequest) {
const pathname = request.nextUrl.pathname;
const search = request.nextUrl.search;
if (/^\/oauth\/[^\/]+\/action\//.test(pathname)) {
// /oauth/:uid/action/:rest*
// 백엔드로 그대로 전달
const url = new URL(request.nextUrl.pathname + request.nextUrl.search, process.env.API_BASE);
return NextResponse.rewrite(url);
}
let cookieLocale = request.cookies.get('locale')?.value;
if (!locales.includes(cookieLocale ?? '')) {
cookieLocale = undefined;
}
let resp;
let matchingLocale;
if (
['/signup/email', '/signup/create', '/password/email', '/password/change'].includes(pathname) ||
/^\/group\/[^\/]+\/membership$/.test(pathname) ||
/^\/session\/[^\/]+$/.test(pathname) ||
/^\/oauth\/[^\/]+$/.test(pathname)
) {
matchingLocale = cookieLocale ?? getLocale(request);
const headers = new Headers(request.headers);
headers.set('x-new-locale', matchingLocale);
resp = NextResponse.next({
request: { headers },
});
} else {
matchingLocale = locales.find(
locale => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`
);
if (matchingLocale == null) {
matchingLocale = cookieLocale ?? getLocale(request);
resp = NextResponse.redirect(
new URL(`/${matchingLocale}${pathname}${search}`, request.url)
);
} else {
const headers = new Headers(request.headers);
headers.set('x-new-locale', matchingLocale);
resp = NextResponse.next({
request: { headers },
});
}
}
if (matchingLocale !== cookieLocale) {
resp.cookies.set('locale', matchingLocale, { path: '/' });
}
return resp;
}
export const config = {
matcher: [
'/((?!_next|api|favicon\.ico).*)',
],
};