-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathmiddleware.ts
74 lines (60 loc) · 2.18 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
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { MiddlewareRequest } from '@netlify/plugin-nextjs/middleware'
export async function middleware(req: NextRequest) {
let response
const {
nextUrl: { pathname },
} = req
const request = new MiddlewareRequest(req)
if (pathname.startsWith('/static')) {
// Unlike NextResponse.next(), this actually sends the request to the origin
const res = await request.next()
const message = `This was static but has been transformed in ${req.geo.city}`
// Transform the response HTML and props
res.replaceText('p[id=message]', message)
res.setPageProp('message', message)
res.setPageProp('showAd', true)
return res
}
if (pathname.startsWith('/api/hello')) {
// Add a header to the request
req.headers.set('x-hello', 'world')
return request.next()
}
if (pathname.startsWith('/headers')) {
// Add a header to the rewritten request
req.headers.set('x-hello', 'world')
return request.rewrite('/api/hello')
}
if (pathname.startsWith('/cookies')) {
response = NextResponse.next()
response.cookies.set('netlifyCookie', 'true')
return response
}
if (pathname.startsWith('/shows')) {
if (pathname.startsWith('/shows/rewrite-absolute')) {
response = NextResponse.rewrite(new URL('/shows/100', req.url))
response.headers.set('x-modified-in-rewrite', 'true')
}
if (pathname.startsWith('/shows/rewrite-external')) {
response = NextResponse.rewrite('http://example.com/')
response.headers.set('x-modified-in-rewrite', 'true')
}
if (pathname.startsWith('/shows/rewriteme')) {
const url = req.nextUrl.clone()
url.pathname = '/shows/100'
response = NextResponse.rewrite(url)
response.headers.set('x-modified-in-rewrite', 'true')
}
if (!response) {
response = NextResponse.next()
}
if (pathname.startsWith('/shows/static')) {
response.headers.set('x-middleware-date', new Date().toISOString())
}
response.headers.set('x-modified-edge', 'true')
response.headers.set('x-is-deno', 'Deno' in globalThis ? 'true' : 'false')
return response
}
}