Next.js Discord

Discord Forum

Working with Route Handlers in Server Components

Unanswered
Scottish Fold posted this in #help-forum
Open in Discord
Scottish FoldOP
I have a project that requires calling to a database to receive some JSON data which I then use in the component. However, if self-hosters of my application don't want to provide their own database and want to have access to the data in my database, I have a system to pass in a URL of the application with the database, which gets passed into SWR.

I want to find a way to either fetch the local route handlers or a custom url inside of server components. I know that you can't really do that because the server doesn't have access to the base url when rendering. Is this possible? Apologies if I'm not making sense, I'd be happy to clarify more if you need me to.

6 Replies

Scottish FoldOP
I've seen something like this with Nuxt, is this possible with Next?
so basically I want to be able to call route handlers inside server components if at all possible
unfortunately no, it's not possible
well, you can make a map of route handlers like
import { GET as apiCount } from "@/app/api/count/route.ts";

export const routeHandlerMap = {
  "/api/count": apiCount,
};

then call it like
const response = await routeHandlerMap["/api/count"](request)

but still, that's a workaround at best. nextjs doesnt support this.
Scottish FoldOP
where would I get the request object to pass into it?
@Scottish Fold where would I get the request object to pass into it?
well you need to make it yourself, like const request = new Request(...) https://developer.mozilla.org/en-US/docs/Web/API/Request/Request

but well... just make the route map yourself in a way that doesn't require using the Request class. for example, instead of importing the GET handler, import the getCount function that you use inside that GET handler