Accessing pathname in Next.js generateMetadata
Can’t access the router in generateMetadata
, and using params
is inadequate if you need the actual path. Guess we have to pass it through from middleware.
Next.js Discussions suggested invoking set
directly on request.headers
but that was returning null
in generateMetadata
.
Had better success modifying the NextResponse.rewrite
as documented in this Vercel demo.
Example below:
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 type {NextRequest, NextResponse} from 'next/server' | |
export async function middleware(req: NextRequest) { | |
const requestHeaders = new Headers(req.headers) | |
requestHeaders.set('x-request-url', req.url); | |
const res = NextResponse.next({ | |
request: { | |
headers: requestHeaders | |
} | |
}); | |
// other things | |
return res; | |
} |
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
export async function generateMetadata(): Promise<Metadata | null> { | |
const pathname = new URL(headers().get('x-request-url')!).pathname; | |
// other things | |
} |
Published September 10, 2023