Next.js Discord

Discord Forum

Fetch relative path

Answered
Cape lion posted this in #help-forum
Open in Discord
Avatar
Cape lionOP
App Router.
I wrote a serverless function and want to use the appropriate path when using fetch.
const res = await fetch('/api/serverless-example')

But for this I need to use 'use client'

However, if the function component is async, then it must be server-side.
Answered by Maheśvara
1) Since this is an RSC then you won't have access to the current path. This is currently something even I have issues with, but that's just how it works. You can either state the absolute path (you can get this from by storing the value in the .env file) or try to get the path from the headers using next/headers.

2) If you have access to it, you can make use of server actions. I've found that in most cases where I would've used a Route Handler in the past, I ended up using it on one page a single time (maybe on page load) and that's in. Replacing those cases with server actions just made the code more readable and even function better in some cases imo. Only if you're gonna reuse an endpoint on the client side do I think you really need to make use of Route Handlers now.
View full answer

1 Reply

Avatar
1) Since this is an RSC then you won't have access to the current path. This is currently something even I have issues with, but that's just how it works. You can either state the absolute path (you can get this from by storing the value in the .env file) or try to get the path from the headers using next/headers.

2) If you have access to it, you can make use of server actions. I've found that in most cases where I would've used a Route Handler in the past, I ended up using it on one page a single time (maybe on page load) and that's in. Replacing those cases with server actions just made the code more readable and even function better in some cases imo. Only if you're gonna reuse an endpoint on the client side do I think you really need to make use of Route Handlers now.
Answer