Next.js Discord

Discord Forum

Is there a new way of working with the api endpoints?

Unanswered
American Chinchilla posted this in #help-forum
Open in Discord
American ChinchillaOP
I am used to the way of having a src folder, with an api folder inside and inside the api folder, naming files endpoint1.ts to be ables to access /api/endpoint1

Although now I am not able to do that. I also cannot find documentation stating that isnt the case anymore. For context, my new codebase does not have a src folder anymore.

6 Replies

You use route handlers to define api routes in Next13+
https://nextjs.org/docs/app/building-your-application/routing/route-handlers
The way you go about doing it is similar to the way you setup a page to be a valid route.
With a page, you name the folder what you want the page to be on the url path, then put a page.tsx in it to register it.
You do the same for api endpoints, however unlike in Next12, you can put it in any folder, just name the file route.ts
Disclaimer: a path cannot have both route.ts and page.tsx, one will overwrite the other (I believe page takes priority)
Also, just a bit of a tip, a lot of things previously used for api routes can now be replaced by using Server Actions. Of course it's up to you which you prefer to stick with, also which one integrates better with your environment, but I found that a lot of my api endpoint usages were one-off instances and replacing them with server actions made my DX much better.