forked from uniformdev/examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
66 lines (57 loc) · 1.75 KB
/
middleware.ts
File metadata and controls
66 lines (57 loc) · 1.75 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
import { parse } from "cookie";
import { NextRequest, NextResponse } from "next/server";
import {
Context,
CookieTransitionDataStore,
ManifestV2,
UNIFORM_DEFAULT_COOKIE_NAME,
} from "@uniformdev/context";
import { createUniformEdgeMiddleware } from "@uniformdev/context-edge-vercel";
import manifest from "./lib/uniform/context-manifest.json";
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - _next
* - static (static files)
* - favicon.ico (favicon file)
*/
"/(.*?trpc.*?|(?!static|.*\\..*|_next|images|img|api|favicon.ico).*)",
],
};
export async function middleware(request: NextRequest) {
const data = request.headers.get("x-nextjs-data");
const previewDataCookie = request.cookies.get("__next_preview_data");
const {
nextUrl: { search },
} = request;
const urlSearchParams = new URLSearchParams(search);
const params = Object.fromEntries(urlSearchParams.entries());
// disabling middleware in preview or locally
if (
Boolean(previewDataCookie) ||
Boolean(data) ||
params.is_incontext_editing_mode === "true" ||
!process.env.VERCEL_URL
) {
return NextResponse.next();
}
const serverCookieValue = request
? parse(request.headers.get("cookie") ?? "")[UNIFORM_DEFAULT_COOKIE_NAME]
: undefined;
const context = new Context({
defaultConsent: true,
manifest: manifest as ManifestV2,
transitionStore: new CookieTransitionDataStore({
serverCookieValue,
}),
});
const handler = createUniformEdgeMiddleware();
const response = await handler({
context,
origin: new URL(request.url),
request,
});
response.headers.set("Cache-Control", "no-cache, no-store, must-revalidate");
return response;
}