#server side url handling

1 messages · Page 1 of 1 (latest)

strange adder
#

How to access the current url (in app directory) from the server

gaunt sunBOT
#

Hi @strange adder. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

To access the current URL's pathname in the app directory, you can use the usePathname hook, which is a Client Component hook. However, it's important to note that usePathname is not supported in Server Components.

Here's an example of how to use usePathname in a Client Component:

'use client';
 
import { usePathname } from 'next/navigation';
 
export default function ExampleClientComponent() {
 const pathname = usePathname();
 return <>Current pathname: {pathname}</>;
}

Source: usePathname (https://nextjs.org/docs/app/api-reference/functions/use-pathname)

If you need to access request-based data like headers or cookies from the server, you can use the headers() and cookies() functions in the app directory. These functions can be used inside Server Components to retrieve request headers and cookies, respectively.

Example:

// `app` directory
import { cookies, headers } from 'next/headers';
 
async function getData() {
 const authHeader = headers().get('authorization');
 
 return '...';
}
 
export default async function Page() {
 // You can use `cookies()` or `headers()` inside Server Components
 // directly or in your data fetching function
 const theme = cookies().get('theme');
 const data = await getData();
 return '...';
}

Source: Accessing Request Object (https://nextjs.org/docs/pages/building-your-application/upgrading/app-router-migration#accessing-request-object)

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

API Reference for the usePathname hook.

Learn how to upgrade your existing Next.js application from the Pages Router to the App Router.