In SSR when I am using Next.js App Router, How can I get full URL of the current page?
I cannot use window.location.href
as window
is not defined and with useRouter()
I cannot get full URL
In SSR when I am using Next.js App Router, How can I get full URL of the current page?
I cannot use window.location.href
as window
is not defined and with useRouter()
I cannot get full URL
2
Answers
You can use
next/headers
to retrieve the full headers, and then use it to construct the full url.Or you can use headers like
host
,x-forwarded-host
andx-invoke-path
(depending on which headers are set in your case).You are absolutely right, since there is no window object in SSR
window.location.href
can’t be used anduseRouter()
hook is available on the client side only. However withuseRouter
hook you can get the current path name in the SSRPotential Solution
install the package
npm install nextjs-current-url
you can use the
getURL
function fromnextjs-current-url
package. It takesreq
object as input that is available in thegetServerSideProps
.Usage in your component