Last active
July 31, 2024 09:28
-
-
Save asmyshlyaev177/c7512da5186354cfc7e2d7db61fad6dc to your computer and use it in GitHub Desktop.
Access Request object in Nextjs App router
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { headers } from 'next/headers' | |
export default async function Layout({ children }: { children: React.ReactNode }) { | |
// access searchParams | |
const sp = headers().get('searchParams') || '' | |
... | |
} | |
// docs https://nextjs.org/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes | |
export const runtime = 'edge'; | |
// star the gist and couple of my pinned repo if it is useful for you. :) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { NextResponse } from 'next/server' | |
import type { NextRequest } from 'next/server' | |
export function middleware(request: NextRequest) { | |
// .search and .searchParams are incorrect | |
const url = request.url?.includes('_next') ? null : request.url | |
const sp = url?.split?.('?')?.[1] || '' | |
const response = NextResponse.next() | |
if (url !== null) { | |
response.headers.set('searchParams', sp) | |
} | |
return response | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment