For those who are migrating from Nextjs Page-Router to App-outer V13+
I was searching for the method to get the full URL
Hers is how it should be done as recommended by Nextjs Documentation
'use client'
import { useEffect } from 'react'
import { usePathname, useSearchParams } from 'next/navigation'
export function NavigationEvents() {
const pathname = usePathname()
const searchParams = useSearchParams()
useEffect(() => {
const url = `${pathname}?${searchParams}`
console.log(url)
// You can now use the current URL
// ...
}, [pathname, searchParams])
return null
}
Notice that you should use this in a client component, not a server component which means you will need to add "use client" on the top of your component page.
In case you want to do this in a server component, you will need to pass the server component to a client component as props.
Scenario: You need the URL in a server component and you can't use the usePathname and useSearchParams as they are only allowed in client components
So what do the docs recommend in this case (and any case where you want to do something in a server component that requires only a client component.
You do what you want in the client component and then pass the server component to the client component with a prop this prop value will be the value of the URL for example or any other data you want to pass to the server component)
Simple Explanation: you will add a prop to the server component called URL and in the client component you will pass the URL which you get using the usePathname and useSearchParams as a prop value to the URL prop.
And if you are thinking why not import the Server Component directly:
From the docs:
Unsupported Pattern: Importing Server Components into Client
Components The following pattern is not supported. You cannot import a
Server Component into a Client Component:
Here's an explanation from the Docs:
Passing Server Components to Client Components as Props
Links:
Docs about the new router updates: https://nextjs.org/docs/app/api-reference/functions/use-router
Docs about usePathname: https://nextjs.org/docs/app/api-reference/functions/use-pathname
Docs about useSearchParams: https://nextjs.org/docs/app/api-reference/functions/use-search-params