|
| 1 | +import { NextResponse } from 'next/server' |
| 2 | + |
| 3 | +export async function middleware(request) { |
| 4 | + const url = request.nextUrl |
| 5 | + |
| 6 | + // this is needed for tests to get the BUILD_ID |
| 7 | + if (url.pathname.startsWith('/_next/static/__BUILD_ID')) { |
| 8 | + return NextResponse.next() |
| 9 | + } |
| 10 | + |
| 11 | + if (url.pathname === '/old-home') { |
| 12 | + if (url.searchParams.get('override') === 'external') { |
| 13 | + return Response.redirect('https://example.vercel.sh') |
| 14 | + } else { |
| 15 | + url.pathname = '/new-home' |
| 16 | + return Response.redirect(url) |
| 17 | + } |
| 18 | + } |
| 19 | + |
| 20 | + if (url.searchParams.get('foo') === 'bar') { |
| 21 | + url.pathname = '/new-home' |
| 22 | + url.searchParams.delete('foo') |
| 23 | + return Response.redirect(url) |
| 24 | + } |
| 25 | + |
| 26 | + // Chained redirects |
| 27 | + if (url.pathname === '/redirect-me-alot') { |
| 28 | + url.pathname = '/redirect-me-alot-2' |
| 29 | + return Response.redirect(url) |
| 30 | + } |
| 31 | + |
| 32 | + if (url.pathname === '/redirect-me-alot-2') { |
| 33 | + url.pathname = '/redirect-me-alot-3' |
| 34 | + return Response.redirect(url) |
| 35 | + } |
| 36 | + |
| 37 | + if (url.pathname === '/redirect-me-alot-3') { |
| 38 | + url.pathname = '/redirect-me-alot-4' |
| 39 | + return Response.redirect(url) |
| 40 | + } |
| 41 | + |
| 42 | + if (url.pathname === '/redirect-me-alot-4') { |
| 43 | + url.pathname = '/redirect-me-alot-5' |
| 44 | + return Response.redirect(url) |
| 45 | + } |
| 46 | + |
| 47 | + if (url.pathname === '/redirect-me-alot-5') { |
| 48 | + url.pathname = '/redirect-me-alot-6' |
| 49 | + return Response.redirect(url) |
| 50 | + } |
| 51 | + |
| 52 | + if (url.pathname === '/redirect-me-alot-6') { |
| 53 | + url.pathname = '/redirect-me-alot-7' |
| 54 | + return Response.redirect(url) |
| 55 | + } |
| 56 | + |
| 57 | + if (url.pathname === '/redirect-me-alot-7') { |
| 58 | + url.pathname = '/new-home' |
| 59 | + return Response.redirect(url) |
| 60 | + } |
| 61 | + |
| 62 | + // Infinite loop |
| 63 | + if (url.pathname === '/infinite-loop') { |
| 64 | + url.pathname = '/infinite-loop-1' |
| 65 | + return Response.redirect(url) |
| 66 | + } |
| 67 | + |
| 68 | + if (url.pathname === '/infinite-loop-1') { |
| 69 | + url.pathname = '/infinite-loop' |
| 70 | + return Response.redirect(url) |
| 71 | + } |
| 72 | + |
| 73 | + if (url.pathname === '/to') { |
| 74 | + url.pathname = url.searchParams.get('pathname') |
| 75 | + url.searchParams.delete('pathname') |
| 76 | + return Response.redirect(url) |
| 77 | + } |
| 78 | + |
| 79 | + if (url.pathname === '/with-fragment') { |
| 80 | + console.log(String(new URL('/new-home#fragment', url))) |
| 81 | + return Response.redirect(new URL('/new-home#fragment', url)) |
| 82 | + } |
| 83 | +} |
0 commit comments