Using lib vs routes
Unanswered
Japanese Spitz posted this in #help-forum
Japanese SpitzOP
Hey guys, nextjs noob here; what exactly are the differences between lib folder and api routes and where should I put what? Is it ok to have all my logic in the api routes? They're hidden and secure right? Or should I have the routes just forward calls to lib functions and avoid having actual logic past input validation in them? Or maybe a split, like having db calls in lib and rest of logic in routes?
What is the industry standard and why?
Thank you!
What is the industry standard and why?
Thank you!
1 Reply
You can actually make another folder named services, and utilize it for the logic and everything based on the files for say auth.ts for authentication logic. You can use the modern approach of class based code to write things such as:
export class AuthService {...}
Then the class will have several async methods which can be accessed as AtuhService.createUser(), this keeps your code clean and maintainable, you just need to call the service inside your routes.
In the lib folder you can keep those functions which will be used by other files too, so basically reusable things, connection to the DB and other things like this.
For validation and schema you can have a separate folder, named schema where you can use zod for writing schema and types, and zod can easily validate it, you just need to call UserSchema.safeParse(req.body); and it will return the validation results for you.
export class AuthService {...}
Then the class will have several async methods which can be accessed as AtuhService.createUser(), this keeps your code clean and maintainable, you just need to call the service inside your routes.
In the lib folder you can keep those functions which will be used by other files too, so basically reusable things, connection to the DB and other things like this.
For validation and schema you can have a separate folder, named schema where you can use zod for writing schema and types, and zod can easily validate it, you just need to call UserSchema.safeParse(req.body); and it will return the validation results for you.