Next.js Discord

Discord Forum

Using route.ts and page.tsx on the same path

Answered
Silver Fox posted this in #help-forum
Open in Discord
Silver FoxOP
Is it possible to use both route.ts and page.tsx on the same folder? Now I see that GET method from route.ts is working but page.tsx is effectively ignored. But I would like to do some server work in GET method and then render page.tsx. Is it possible?
What I'm trying to achieve is to set initial cookie from GET route handler since I cannot set cookie from server component. Thanks for a help!
Answered by Pollock
From the docs:
But there cannot be a route.js file at the same route segment level as page.js.

You can handle it in middleware, where you can either comapre the pathname (req.nextUrl.pathname === '/your-page') or use matcher (https://nextjs.org/docs/app/building-your-application/routing/middleware#matcher) that will limit where the middleware will run.

Also, not sure what's the cookie for, but you could also trigger server action from a client component on mount or create a separate API endpoint and call it during the server render of your page.
View full answer

5 Replies

Silver FoxOP
but middleware affects all the routes right? Or do you mean that I should compare route urls manually?
Pollock
From the docs:
But there cannot be a route.js file at the same route segment level as page.js.

You can handle it in middleware, where you can either comapre the pathname (req.nextUrl.pathname === '/your-page') or use matcher (https://nextjs.org/docs/app/building-your-application/routing/middleware#matcher) that will limit where the middleware will run.

Also, not sure what's the cookie for, but you could also trigger server action from a client component on mount or create a separate API endpoint and call it during the server render of your page.
Answer
Silver FoxOP
thank you all! I will try option with middleware