generated from timlrx/tailwind-nextjs-starter-blog
-
Notifications
You must be signed in to change notification settings - Fork 6
/
_middleware.ts
52 lines (43 loc) · 1.59 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
import type { NextRequest } from 'next/server'
import { NextResponse } from 'next/server'
// Regex to check whether something has an extension, e.g. .jpg
const PUBLIC_FILE = /\.(.*)$/
export function middleware(request: NextRequest) {
const { nextUrl, headers } = request
const url = nextUrl.clone()
// const languageCookie = request.cookies.get('selectedLanguage')?.value // 쿠키에서 언어 읽기
const language =
request.cookies.get('selectedLanguage')?.value ||
headers.get('accept-language')?.split(',')?.[0].split('-')?.[0].toLowerCase()
try {
if (nextUrl.pathname.startsWith('/_next/image')) {
const imageUrl = nextUrl.searchParams.get('url')
if (imageUrl) {
const newImageUrl = imageUrl.replace(/^\/(en|ko)\//, '/')
nextUrl.searchParams.set('url', newImageUrl)
return NextResponse.rewrite(nextUrl.toString())
}
}
// Early return if it is a public file such as an image or an api call
if (PUBLIC_FILE.test(nextUrl.pathname) || nextUrl.pathname.includes('/api')) {
return undefined
}
if (nextUrl.pathname.startsWith('/en') || nextUrl.pathname.startsWith('/ko')) {
return undefined
}
if (language === 'ko') {
url.pathname = `/ko${nextUrl.pathname}`
return NextResponse.redirect(url)
}
if (language === 'en') {
url.pathname = `/en${nextUrl.pathname}`
return NextResponse.redirect(url)
}
if (nextUrl.pathname.startsWith('/en') || nextUrl.pathname.startsWith('/ko')) {
return undefined
}
return undefined
} catch (error) {
console.log(error)
}
}