Back to Courses

World's Best MERN Stack Course

MERN Tutorial #4: Express Routers πŸ”₯ Creating and Organizing Routes

Welcome, In this tutorial, we'll take a journey into Express.js Routers. We'll start with a quick intro about express routers and then dive into understanding Express Routers. You'll learn how to create a router file, set up routes using router.get, and seamlessly integrate the router into your main server file. We'll also explore more advanced routing techniques with router.route. By the end, you'll have a solid grasp of Express.js routing.

our routes β†’ auth-route.js file

// *----------------------
//* express.Router
// *----------------------

//? In Express.js, express.Router() is a mini Express application without all the server configurations but with the ability to define routes, middleware, and even have its own set of route handlers. It allows you to modularize your routes and middleware to keep your code organized and maintainable.
//* <https://expressjs.com/en/guide/routing.html>
//? Use the express.Router class to create modular, mountable route handlers. A Router instance is a complete middleware and routing system; for this reason, it is often referred to as a β€œmini-app”.

const express = require("express");
const router = express.Router();

// app.get("/", (req, res) => {
//   res.status(200).send("Welcome to thapa technical Mern Series Updated");
// });

router.route("/").get((req, res) => {
  res.status(200).send("Welcome to thapa technical Mern Series Updated");
});

// app.get("/register", (req, res) => {
//   res.status(200).json({ msg: "registration successful" });
// });
router.route("/register").get((req, res) => {
  res.status(200).json({ msg: "registration successful from router" });
});

module.exports = route

our server.js file

const express = require("express");
const app = express();
const router = require("./routes/auth-route");

// Mount the Router: To use the router in your main Express app, you can "mount" it at a specific URL prefix
app.use("/api/auth", router);

const PORT = 5000;
app.listen(PORT, () => {
  console.log(`server is running at port: ${PORT}`);
});