Skip to content

Instantly share code, notes, and snippets.

@asmyshlyaev177
Last active July 31, 2024 09:28
Show Gist options
  • Save asmyshlyaev177/c7512da5186354cfc7e2d7db61fad6dc to your computer and use it in GitHub Desktop.
Save asmyshlyaev177/c7512da5186354cfc7e2d7db61fad6dc to your computer and use it in GitHub Desktop.
Access Request object in Nextjs App router
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. :)
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