Next.js Discord

Discord Forum

Existential crisis regarding code structuring

Unanswered
Kawakawa posted this in #help-forum
Open in Discord
KawakawaOP
Hello

I'm having bit of a existential crisis regarding code structuring and would like to discuss it with nextjs community.

I've looked at couple of big open source projects that use nextjs and they have one thing in common - everything is in getServerSideProps function or in /pages/api/some-endpoint.ts API handler. By everything I mean session checks, permissions, data validation, database queries, 3rd party requests etc, they are all in one function.

My previous projects used expressjs so I might be little biased here, but I used to separate my code into models (database queries), controllers, reusable middlewares (session checks, permissions) etc. I've tried to follow the same pattern with my nextjs project too but I've hit some blockers.

I can't understand, why have these projects done it that way. It goes against everything I've learned through out my career.


Little bit about my blockers.

Main problem I'm facing now is that I can't find a good way to create controllers that are usable in both API handler and getServerSideProps. First, their req & res objects are different (eg. getServerSideProps req object is missing query) and second, how to return results - for getServerSideProps I need to return { notFound: true } for 404, but for API handler, I need to set HTTP statusCode. Simple wrapper could be written here but I can't seem to find way to differentiate between API handler & getServerSideProps.

Why do I want to do that? Because there are pages where I'd like to use getServerSideProps for initial data, and have API endpoint that returns same data incase I want to update my view with react-query. Having one controller for both would make sure that I don't need to write same logic twice, and I could infer types from my controller function.

Sorry if it's a bit of a ramble.

Thanks in advance.

1 Reply

i understand. Vercel has introduced a brand new, different design, named App Router, where you can move fetch apis into React Server Components that consume data. The codes you see is unfortunately the previous way named Page Router.