Organizing Your Node.js REST API with Express Router and Input Validation
Step 1: Why Organize Routes?
Imagine your code is like a big kitchen. 🍳
If all the ingredients, pots, and pans are thrown in one corner, cooking gets messy fast!
Right now, all our API routes are in server.js. That’s fine for small projects, but as we grow, it’s better to organize routes in separate files. This makes your project clean, readable, and easier to maintain.
Step 2: Create a Routes Folder
-
In your project folder, make a new folder called
routes:
-
Inside
routes, create a file calledusers.js.
This file will hold all the user-related routes.
Step 3: Move Routes into users.js
In routes/users.js, put this code:
Notice how we added simple input validation. If someone tries to create a user without a name or email, our API will politely refuse. 😊
Step 4: Update server.js
Now we need to tell server.js to use this new route file:
Now, all user routes live in routes/users.js and server.js stays clean and simple.
Step 5: Test Everything
-
Open Postman or use
curlto check that all endpoints (GET /users,POST /users, etc.) still work. -
Try sending invalid data to
POST /usersto see the validation in action.
Step 6: Next Tips from Your Coding Grandpa 😄
-
You can create more route files for other features like
products.jsortasks.js. -
Learn about Express middleware to add authentication or logging.
-
Always keep routes small and organized—like tidy drawers in your kitchen!