-
Notifications
You must be signed in to change notification settings - Fork 4
/
middleware.ts
210 lines (179 loc) · 5.52 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
import createIntlMiddleware from 'next-intl/middleware';
import { NextRequest, NextResponse } from 'next/server';
import { ApolloClient, InMemoryCache, from } from '@apollo/client';
import possibleTypes from './common/__generated__/possible_types.json';
import { GET_PLANS_BY_HOSTNAME } from './queries/get-plans';
import {
GetPlansByHostnameQuery,
GetPlansByHostnameQueryVariables,
} from './common/__generated__/graphql';
import { stripLocaleAndPlan } from './utils/urls';
import { UNPUBLISHED_PATH } from './constants/routes';
import {
getHttpLink,
operationEnd,
operationStart,
} from './utils/apollo.utils';
import { captureException } from '@sentry/nextjs';
import {
convertPathnameFromInvalidLocaleCasing,
convertPathnameFromLegacy,
getLocaleAndPlan,
getSearchParamsString,
isAuthenticated,
isLegacyPathStructure,
isPlanPublished,
isRestrictedPlan,
rewriteUrl,
} from './utils/middleware.utils';
import { tryRequest } from './utils/api.utils';
const apolloClient = new ApolloClient({
cache: new InMemoryCache({
typePolicies: {
Plan: {
/**
* Prevent cache conflicts between multi-plan plans when visited via basePath
* (e.g. umbrella.city.gov/x-plan) vs a dedicated plan subdomain (e.g. x-plan.city.gov/)
*/
keyFields: ['id', 'domain', ['hostname']],
},
},
// https://www.apollographql.com/docs/react/data/fragments/#defining-possibletypes-manually
possibleTypes: possibleTypes.possibleTypes,
}),
link: from([operationStart, operationEnd, getHttpLink()]),
});
export const config = {
matcher: [
/*
* Match all paths except for:
* 1. /api routes
* 2. /_next (Next.js internals)
* 3. /_static (inside /public)
* 4. all root files inside /public
*/
'/((?!api/|_next/|_static/|static/|[\\w-]+\\.\\w+).*)',
],
};
const clearCacheIfTimedOut = (function handleCacheTTL() {
let timeCached: number | null = null;
const THIRTY_MINS = 30 * 60 * 1000;
return () => {
if (!timeCached) {
timeCached = Date.now();
} else if (Date.now() - timeCached > THIRTY_MINS) {
timeCached = Date.now();
apolloClient.clearStore();
}
};
})();
export async function middleware(request: NextRequest) {
const url = request.nextUrl;
const { pathname } = request.nextUrl;
const host = request.headers.get('host');
const protocol = request.headers.get('x-forwarded-proto');
const hostUrl = new URL(`${protocol}://${host}`);
const hostname = hostUrl.hostname;
console.log(`
⚙ Middleware ${url}
↝ protocol: ${protocol}
↝ pathname: ${pathname}
↝ hostname: ${hostname}
`);
// Redirect the root application locally to `sunnydale` tenant
if (hostname === 'localhost') {
return NextResponse.redirect(new URL(`http://sunnydale.${host}`));
}
if (pathname === '/_health') {
url.pathname = '/api/health';
return NextResponse.rewrite(url);
}
if (pathname === '/_invalidate-middleware-cache') {
await apolloClient.clearStore();
return NextResponse.json({
message: 'Middleware cache cleared',
});
}
if (!isAuthenticated(request, hostname)) {
url.pathname = '/api/auth';
return NextResponse.rewrite(url);
}
clearCacheIfTimedOut();
const { data, error } = await tryRequest(
apolloClient.query<
GetPlansByHostnameQuery,
GetPlansByHostnameQueryVariables
>({
query: GET_PLANS_BY_HOSTNAME,
variables: { hostname },
})
);
if (error || !data?.plansForHostname?.length) {
if (error) {
captureException(error, { extra: { hostname, ...error } });
}
return NextResponse.rewrite(new URL('/404', request.url));
}
const { parsedLocale, parsedPlan, isLocaleCaseInvalid } = getLocaleAndPlan(
pathname,
data.plansForHostname
);
if (!parsedPlan) {
return NextResponse.rewrite(new URL('/404', request.url));
}
if (isLegacyPathStructure(pathname, parsedLocale, parsedPlan)) {
const newPathname = convertPathnameFromLegacy(
pathname,
parsedLocale,
parsedPlan
);
return NextResponse.redirect(new URL(newPathname, request.url));
}
if (isLocaleCaseInvalid) {
const newPathname = convertPathnameFromInvalidLocaleCasing(
pathname,
parsedLocale
);
return NextResponse.redirect(new URL(newPathname, request.url));
}
const handleI18nRouting = createIntlMiddleware({
locales: [parsedPlan.primaryLanguage, ...(parsedPlan.otherLanguages ?? [])],
defaultLocale: parsedPlan.primaryLanguage,
localePrefix: 'as-needed',
localeDetection: false,
});
const response = handleI18nRouting(request);
if (isRestrictedPlan(parsedPlan) || !isPlanPublished(parsedPlan)) {
// Pass the status message to the unpublished page as search params
const message = parsedPlan.domain?.statusMessage;
const queryParams = message
? `?${new URLSearchParams({
message,
}).toString()}`
: '';
const rewrittenUrl = new URL(
`/${hostname}/${parsedLocale}${UNPUBLISHED_PATH}${queryParams}`,
request.url
);
return rewriteUrl(
request,
response,
hostUrl,
rewrittenUrl,
parsedPlan.identifier
);
}
const searchParams = getSearchParamsString(request);
const strippedPath = stripLocaleAndPlan(parsedPlan, parsedLocale, pathname);
const rewrittenUrl = new URL(
`/${hostname}/${parsedLocale}/${parsedPlan.id}/${strippedPath}${searchParams}`,
request.url
);
return rewriteUrl(
request,
response,
hostUrl,
rewrittenUrl,
parsedPlan.identifier
);
}