Skip to Content
We Are Launched v1.0

1. What is express.static()?

express.static() is a built-in Express middleware that serves static files (like HTML, CSS, images, or JavaScript) from a specified folder. When a client requests a file, Express automatically sends it without needing a custom route.

Why use it?

  • Simplifies serving assets like stylesheets, scripts, or images for your web app.
  • No need to write routes for each file.

📦 Example:

  1. Create a folder named public in your project with an index.html file:
<!-- public/index.html --> <h1>Welcome to my site!</h1>
  1. Set up your Express app:
const express = require("express"); const app = express(); const port = 3000; // Serve static files from the 'public' folder app.use(express.static("public")); app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); });

⚙️ How it works:


2. How do you handle errors in Express?

Express allows you to handle errors using special error-handling middleware. This middleware has four parameters (err, req, res, next) and is called when an error occurs in your app. You can use it to send custom error messages or log errors.

🔹 Steps:

  • Define error-handling middleware at the end of your middleware stack.
  • Use next(err) in routes to pass errors to this middleware.
  • Send a response with an error message and status code.

📦 Example:

const express = require("express"); const app = express(); const port = 3000; app.get("/", (req, res, next) => { try { throw new Error("Something went wrong!"); } catch (err) { next(err); // Pass error to error-handling middleware } }); // Error-handling middleware app.use((err, req, res, next) => { console.error(err.message); // Log the error res.status(500).send("Oops, something broke!"); }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); });

⚙️ How it works:

The / route throws an error, which is passed to the error-handling middleware via next(err). The middleware catches the error, logs it, and sends a 500 status with a message. Visiting http://localhost:3000 shows: Oops, something broke!.


3. What is the difference between app.get() and app.use()?

In Express, app.get() and app.use() serve different purposes:

app.get(path, callback) Defines a route handler for GET requests to a specific URL path. It’s used to send responses for specific routes and HTTP methods.

app.use([path], callback) Applies middleware or route handlers to all HTTP methods (GET, POST, etc.) for a given path (or all paths if no path is specified). It’s commonly used for middleware.

Key Differences:

  • app.get() is specific to GET requests; app.use() applies to all HTTP methods.
  • app.get() is typically used for routes; app.use() is used for middleware or general-purpose handlers.
  • app.use() can take an optional path, while app.get() always requires a path.

📦 Example:

const express = require("express"); const app = express(); const port = 3000; // Middleware with app.use app.use((req, res, next) => { console.log("This runs for ALL requests"); next(); }); // Route with app.get app.get("/home", (req, res) => { res.send("Welcome to the home page!"); }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); });

⚙️ How it works:

  • The app.use middleware logs a message for all requests, regardless of the URL or method.
  • The app.get route only responds to GET requests to /home.
  • Visiting http://localhost:3000/home logs the middleware message and shows: Welcome to the home page!.

4. How do you serve HTML files in Express?

To serve HTML files in Express, you use res.sendFile() to send a specific file to the client. The path module is often used to create absolute file paths to avoid errors across different operating systems.

🔹 Steps:

  1. Create an HTML file in your project (e.g., public/index.html).
  2. Use res.sendFile() with the absolute path to the file.
  3. Optionally, use express.static() to serve the entire folder containing the HTML file.

📦 Example:

  • Create public/index.html:
<h1>My Express Website</h1> <p>Welcome to my page!</p>
  • Set up your Express app: javascript
const express = require('express'); const path = require('path'); const app = express(); const port = 3000; app.get('/', (req, res) => { res.sendFile(path.join(\_\_dirname, 'public', 'index.html')); }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); });

⚙️ How it works:

  • path.join(\_\_dirname, 'public', 'index.html') creates the absolute path to index.html.
  • Visiting http://localhost:3000 displays the HTML
  • content: My Express Website and Welcome to my page!.

5. What is the purpose of next() in middleware?

In Express middleware, next() is a function that passes control to the next middleware or route handler in the chain. If you don’t call next(), the request will hang, and the client won’t receive a response.

Why is it needed?

Middleware often performs tasks (e.g., logging, authentication) and then hands off the request to the next handler. next() ensures the request continues processing.

📦 Example:

const express = require("express"); const app = express(); const port = 3000; // Middleware 1 app.use((req, res, next) => { console.log("Middleware 1: Logging request"); next(); // Move to the next middleware }); // Middleware 2 app.use((req, res, next) => { console.log("Middleware 2: Adding timestamp"); req.timestamp = new Date(); next(); // Move to the route }); // Route app.get("/", (req, res) => { res.send(`Request processed at: ${req.timestamp}`); }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); });

⚙️ How it works:

  • Middleware 1 logs a message and calls next() to pass control.
  • Middleware 2 adds a timestamp to req and calls next().
  • The route uses the timestamp and sends a response.
  • Visiting http://localhost:3000 shows something like: Request processed at: 2025-07-28T16:34:00.000Z.

6. How do you handle 404 errors in Express?

A 404 error occurs when a client requests a route that doesn’t exist. In Express, you handle 404 errors by adding a middleware function at the end of your middleware and route stack. This middleware catches any unmatched requests and sends a 404 response.

🔹 Steps:

  1. Place the 404 middleware after all routes.
  2. Use res.status(404) to set the HTTP status and send a response.

📦 Example:

const express = require("express"); const app = express(); const port = 3000; app.get("/", (req, res) => { res.send("Home page"); }); // 404 middleware (must be last) app.use((req, res) => { res.status(404).send("Page not found!"); }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); });

⚙️ How it works:


7. What is Express Router?

Express Router is a feature in Express.js that lets you group related routes and middleware into a separate, reusable module. It’s like a mini Express app that handles specific routes, making your code more organized and easier to maintain, especially for large apps.

Why use it?

  • Keeps your main app.js file clean by moving routes to separate files.
  • Makes routes reusable across different parts of your app.
  • Simplifies managing related routes (e.g., all user-related routes in one place).

📦 Example:

  • Create a file named userRoutes.js:
const express = require("express"); const router = express.Router(); router.get("/", (req, res) => { res.send("List of users"); }); router.get("/:id", (req, res) => { res.send(`User with ID: ${req.params.id}`); }); module.exports = router;
  • Use it in app.js:
const express = require("express"); const app = express(); const port = 3000; const userRoutes = require("./userRoutes"); app.use("/users", userRoutes); app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); });

⚙️ How it works:


8. How do you use Express Router?

Using Express Router involves creating a router instance, defining routes on it, and then mounting it on your Express app with app.use(). This lets you organize routes into separate files and attach them to specific paths.

🔹 Steps:

  1. Create a router in a separate file (e.g., routes/users.js).
  2. Define routes using router.get(), router.post(), etc. Export the router and use it in your main app with app.use().

📦 Example:

  • Create routes/users.js:
const express = require("express"); const router = express.Router(); router.get("/", (req, res) => { res.send("All users"); }); router.get("/profile", (req, res) => { res.send("User profile page"); }); module.exports = router;
  • Use it in app.js:
const express = require("express"); const app = express(); const port = 3000; const userRoutes = require("./routes/users"); app.use("/users", userRoutes); app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); });

⚙️ How it works:

Last updated on