mirror of
				https://github.com/theoludwig/theoludwig.git
				synced 2025-10-14 20:23:25 +02:00 
			
		
		
		
	Improvements: - Hide switch theme input (ugly little white square) - i18n without subpath (e.g: /fr or /en), same url whatever the locale used
		
			
				
	
	
		
			54 lines
		
	
	
		
			1.4 KiB
		
	
	
	
		
			TypeScript
		
	
	
	
	
	
			
		
		
	
	
			54 lines
		
	
	
		
			1.4 KiB
		
	
	
	
		
			TypeScript
		
	
	
	
	
	
| import { NextResponse } from 'next/server'
 | |
| import type { NextRequest } from 'next/server'
 | |
| import { match } from '@formatjs/intl-localematcher'
 | |
| import Negotiator from 'negotiator'
 | |
| 
 | |
| import type { AvailableLocale } from '@/utils/constants'
 | |
| import {
 | |
|   COOKIE_MAX_AGE,
 | |
|   DEFAULT_LOCALE,
 | |
|   AVAILABLE_LOCALES
 | |
| } from '@/utils/constants'
 | |
| 
 | |
| export const middleware = (request: NextRequest): NextResponse => {
 | |
|   const response = NextResponse.next()
 | |
| 
 | |
|   let locale = request.cookies.get('locale')?.value
 | |
|   if (
 | |
|     locale == null ||
 | |
|     !AVAILABLE_LOCALES.includes(locale as AvailableLocale)
 | |
|   ) {
 | |
|     const headers = {
 | |
|       'accept-language':
 | |
|         request.headers.get('accept-language') ?? DEFAULT_LOCALE
 | |
|     }
 | |
|     const languages = new Negotiator({ headers }).languages()
 | |
|     locale = match(languages, AVAILABLE_LOCALES.slice(), DEFAULT_LOCALE)
 | |
|     response.cookies.set('locale', locale, {
 | |
|       path: '/',
 | |
|       maxAge: COOKIE_MAX_AGE
 | |
|     })
 | |
|   }
 | |
| 
 | |
|   const theme = request.cookies.get('theme')?.value ?? 'dark'
 | |
|   response.cookies.set('theme', theme, {
 | |
|     path: '/',
 | |
|     expires: COOKIE_MAX_AGE
 | |
|   })
 | |
| 
 | |
|   return response
 | |
| }
 | |
| 
 | |
| export const config = {
 | |
|   matcher: [
 | |
|     /*
 | |
|      * Match all request paths except for the ones starting with:
 | |
|      * - api (API routes)
 | |
|      * - _next/static (static files)
 | |
|      * - _next/image (image optimization files)
 | |
|      * - favicon.ico (favicon file)
 | |
|      */
 | |
|     '/((?!api|_next/static|_next/image|favicon.ico).*)'
 | |
|   ]
 | |
| }
 |