DEV Community

Discussion on: Why I choose NextJS over CRA for new projects

Collapse
 
zalithka profile image
Andre Greeff

this is one point that causes quite a bit of confusion, but these API routes are actually added inside the my-app/pages/ folder, not alongside it... as per the documentation you linked to:

Any file inside the folder pages/api is mapped to /api/* and will be treated as an API endpoint instead of a page. They are server-side only bundles and won't increase your client-side bundle size.

so basically:

my-app/
- pages/
- - index.tsx // URL "example.com"
- - about/
- - - index.tsx // URL "example.com/about"
- - api/
- - - index.tsx // URL "example.com/api"
- - - about/
- - - - index.tsx // URL "example.com/api/about"
Enter fullscreen mode Exit fullscreen mode

disclaimer: I am still learning my way around Next.js myself, so I'm far from an expert on the topic, but this point has already caught me out a few times now..

perhaps it would've been more "logical" to have src/pages for reserved for "frontend" and src/api reserved for "backend"? ..and now suddenly I'm wondering if it might change to that one day.

Thread Thread
 
andyrewlee profile image
Andrew Lee • Edited

Oh that was a mistake on my part. The docs do indicate that the api/ should be inside of pages/. I'm surprised that it still works even when it is outside of pages/. Thanks for clarifying.

Thread Thread
 
zalithka profile image
Andre Greeff

hmm.. I really shouldn't be digging into this now (I'm at work, so I need to do work stuff), but......

after a little searching, I found an interesting part of the NextJS docs, which states:

Pages can also be added under src/pages as an alternative to the root pages directory.

The src directory is very common in many apps and Next.js supports it by default.

which goes on to list a caveat for this:

src/pages will be ignored if pages is present in the root directory

so after a quick chat with my friend Charlie (yes, the unicorn), we have a theory that perhaps there might be something similar with the API routes handling? maybe the pages/ parent folder path is "optional" due to some internal conditional checks and/or default fallbacks?? honestly not sure.

FWIW, I did see something in the configuration side about redirecting api/ URL requests to a custom folder in the project, not sure which tab that was in now though.

anyways, I need to get on with my day job now, so I'll go play with NextJS a bit more when I get home this evening. (: