Facebook Pixel

How to Build a REST API in Node.js: Step by Step

Building a REST API in Node.js is a learnable process. Here is the step-by-step guide.

How to Build a REST API in Node.js: Step by Step

Building a REST API in Node.js is a learnable process. Here is the step-by-step guide.

Step 1: Set Up the Project

npm init -y. Install express, mongoose, dotenv, cors, helmet. Install nodemon as a dev dependency. Add scripts: start, dev.

Step 2: Create the Folder Structure

src/
  config/
  middlewares/
  models/
  routes/
  controllers/
  utils/
  app.js
  server.js

Step 3: Set Up Express

In src/app.js: create the app, add express.json, cors, helmet, mount routers, register the error handler.

In src/server.js: import app, connect to the database, call app.listen on process.env.PORT || 3000.

Step 4: Connect to MongoDB

In src/config/db.js: connect with mongoose.connect(process.env.MONGODB_URI). Handle connection events. Export the connection.

Step 5: Define Your First Schema

In src/models/user.js: define the user schema (firstName, email, passwordHash, age, gender, photoUrl, about). Add timestamps: true. Mark passwordHash with select: false. Add a unique index on email.

Step 6: Write Routes

In src/routes/users.js: create a router with GET /, POST /, GET /:id, PATCH /:id, DELETE /:id. Bind each to a controller function.

Step 7: Write Controllers

In src/controllers/userController.js: write listUsers, createUser, getUser, updateUser, deleteUser. Each uses the User model. Use async/await. Wrap with asyncHandler.

Step 8: Add Input Validation

Use Zod or express-validator. Write a validate(schema) middleware. Apply per route. Return 400 with errors on invalid input.

Step 9: Add Error Handling

In src/middlewares/error.js: write a four-parameter error handler. Use a custom ApiError class. Never leak stack traces in production.

Step 10: Add Auth

Implement signup, login, logout. Hash passwords with bcrypt. Issue JWT. Store in httpOnly cookies. Protect routes with an auth middleware.

Step 11: Test the API

Use Postman or supertest. Test happy paths and error paths. Run tests in CI.

Step 12: Add Security Middlewares

helmet, cors, express-rate-limit, express-mongo-sanitize, xss-clean, hpp. Most are one-liners with big payoff.

Step 13: Add Logging

morgan for dev, pino-http for production. Log method, path, status, response time. Ship logs centrally.

Step 14: Document the API

Swagger (OpenAPI), Postman collection, or a markdown doc with examples. Without docs, only the author knows how to call it.

Step 15: Deploy

Deploy on a VPS or managed service. Use Nginx in front. Use HTTPS. Run with PM2 or systemd. Set env vars. Add a domain.

The Takeaway

Build a REST API in Node.js: set up the project, create folder structure, set up Express, connect to MongoDB, define schemas, write routes and controllers, add validation, error handling, auth, security middlewares, logging, tests, documentation, and deployment. One step at a time.

Set up the project, create folder structure, set up Express, connect to MongoDB, define schemas, write routes and controllers, add validation, error handling, auth, security middlewares, logging, tests, documentation, and deploy. One step at a time.

Initialize the project with npm init -y, install express, mongoose, dotenv, cors, helmet, and nodemon as a dev dependency. Add start and dev scripts. Then create the folder structure.

Separate folders for config, middlewares, models, routes, controllers, and utils. Keep app.js (Express app) and server.js (server startup) separate. One file per concern. This is the cleanest layout for a growing API.

After schemas, routes, controllers, validation, and error handling. Auth depends on user schemas, password hashing, and tokens. It is a natural step after you can store and retrieve users.

Deploy. Use a VPS or managed service, Nginx in front, HTTPS, PM2 or systemd for process management, env vars for config, and a custom domain. Add monitoring and logging once in production.

Ready to master Node.js completely?

Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.