-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
87 lines (60 loc) · 2.54 KB
/
Copy pathproxy.ts
File metadata and controls
87 lines (60 loc) · 2.54 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import type { SiteType } from '~/lib/config';
import { LOCALE_COOKIE, LOCALE_COOKIE_MAX_AGE, isSupportedLocale, negotiateLocale } from '~/lib/i18n';
import diegocoxtaCom from '~/app/diegocoxta.com/config';
import diegocostaComBr from '~/app/diegocosta.com.br/config';
import diegocostaMe from '~/app/diegocosta.me/config';
const SITES: readonly SiteType[] = [diegocostaComBr, diegocoxtaCom, diegocostaMe];
export function proxy(request: NextRequest) {
const { pathname } = request.nextUrl;
const url = request.nextUrl.clone();
let hostname = (request.headers.get('host') || '').split(':')[0];
const { DEV_SITE, NODE_ENV } = process.env;
if (hostname === 'localhost' && DEV_SITE) {
hostname = DEV_SITE;
}
let pathPrefix = '';
let routePath = pathname;
if (hostname.endsWith('.vercel.app') || (hostname === 'localhost' && !DEV_SITE)) {
const [, maybeDomain, ...rest] = pathname.split('/');
const matchedSite = SITES.find((site) => site.domain === maybeDomain);
if (matchedSite) {
hostname = matchedSite.domain;
pathPrefix = `/${maybeDomain}`;
routePath = `/${rest.join('/')}`;
}
}
const site = SITES.find((s) => s.domain === hostname) ?? SITES[0];
hostname = site.domain;
const { locales } = site;
const assetMetadata =
/^\/(icon|apple-icon|opengraph-image|twitter-image|robots\.txt|manifest\.json|sitemap\.xml)(\/|$)|\.[^/]+$/;
const onlyOneLanguageOrAssetMetadata = locales.length < 2 || assetMetadata.test(routePath);
if (onlyOneLanguageOrAssetMetadata) {
url.pathname = `/${hostname}${routePath}`;
return NextResponse.rewrite(url);
}
const firstSegment = routePath.split('/')[1];
const cookie = request.cookies.get(LOCALE_COOKIE)?.value;
const withoutLanguagePrefix = !isSupportedLocale(locales, firstSegment);
if (withoutLanguagePrefix) {
const locale = negotiateLocale(locales, cookie, request.headers.get('accept-language'));
url.pathname = `${pathPrefix}/${locale}${routePath === '/' ? '' : routePath}`;
return NextResponse.redirect(url);
}
url.pathname = `/${hostname}${routePath}`;
const response = NextResponse.rewrite(url);
if (cookie !== firstSegment) {
response.cookies.set(LOCALE_COOKIE, firstSegment, {
path: '/',
maxAge: LOCALE_COOKIE_MAX_AGE,
sameSite: 'lax',
secure: NODE_ENV === 'production',
});
}
return response;
}
export const config = {
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
};