-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
60 lines (50 loc) · 1.97 KB
/
Copy pathmiddleware.ts
File metadata and controls
60 lines (50 loc) · 1.97 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
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
import { updateSession } from '@/lib/utils/supabase/middleware'
import { NextResponse, type NextRequest } from "next/server"
import { match } from '@formatjs/intl-localematcher'
import Negotiator from 'negotiator'
export async function middleware(request: NextRequest) {
const response = await updateSession(request)
const { pathname } = request.nextUrl
// skip middle ware if static file or asset
if (pathname.startsWith('/_next') || pathname.startsWith('/favicon.ico')) {
return response
}
const locales = ['en', 'de']
const defaultLocale = 'en'
const headers = { 'accept-language': 'en,de;0.7' }
const languages = new Negotiator({ headers }).languages()
const cookieLocale = request.cookies.get('site_locale')?.value
const matchedLocale = match(languages, locales, defaultLocale) // -> 'en-US' or 'de
const activeLocale = cookieLocale || matchedLocale
const pathnameLocale = locales.find((locale) =>
pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`
);
if (pathnameLocale) {
if (pathnameLocale !== activeLocale) {
response.cookies.set('site_locale', pathnameLocale, { path: '/' })
}
// Extract the locale from the pathname
return response
}
// Redirect if there is no locale
request.nextUrl.pathname = `/${activeLocale}${pathname}`
// e.g. incoming request is /products
// The new URL is now /en-US/products
if (!cookieLocale) {
response.cookies.set('site_local', activeLocale, { path: '/' })
}
return NextResponse.redirect(request.nextUrl, 308)
}
export const config = {
matcher: [
/*
* Match all request paths except:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
* - images - .svg, .png, .jpg, .jpeg, .gif, .webp
* Feel free to modify this pattern to include more paths.
*/
"/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)",
],
}