How can I redirect users to a 404.html page in a Node.js server?

How can I redirect users to a 404.html page in a Node.js server?

I’m building a server in pure Node.js (without Express) and want to redirect users to a 404.html page when they enter an invalid URL.

Most solutions I found are for Express, but I need a way to handle this in plain Node.js. How can I achieve this?

Basic Node.js HTTP Server with 404 Redirect :

const http = require('http');
const fs = require('fs');
const path = require('path');

const server = http.createServer((req, res) => {
  // Define valid routes here
  const validRoutes = ['/home', '/about']; 

  // Check if the request URL matches any valid routes
  if (!validRoutes.includes(req.url)) {
    // If not, serve the 404.html page
    const filePath = path.join(__dirname, '404.html');
    fs.readFile(filePath, (err, data) => {
      if (err) {
        res.writeHead(500, { 'Content-Type': 'text/plain' });
        res.end('Error loading 404 page.');
      } else {
        res.writeHead(404, { 'Content-Type': 'text/html' });
        res.end(data);
      }
    });
  } else {
    // Handle valid routes
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Valid route!');
  }
});

server.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});

Serve 404 for Undefined Routes :

const http = require('http');
const fs = require('fs');
const path = require('path');

const server = http.createServer((req, res) => {
  const validRoutes = ['/home', '/about'];

  if (validRoutes.indexOf(req.url) === -1) {
    // Send 404 response and serve 404.html if route doesn't exist
    fs.readFile(path.join(__dirname, '404.html'), (err, data) => {
      if (err) {
        res.writeHead(500, { 'Content-Type': 'text/plain' });
        res.end('500 Server Error');
      } else {
        res.writeHead(404, { 'Content-Type': 'text/html' });
        res.end(data);
      }
    });
  } else {
    // Serve your valid route content here
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('This is a valid route');
  }
});

server.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});

Using a Default Catch-All for 404 :

const http = require('http');
const fs = require('fs');
const path = require('path');

const server = http.createServer((req, res) => {
  const validRoutes = ['/home', '/about'];

  // If the route is not valid, serve the 404.html page
  if (!validRoutes.includes(req.url)) {
    fs.readFile(path.join(__dirname, '404.html'), (err, data) => {
      res.writeHead(404, { 'Content-Type': 'text/html' });
      res.end(data);
    });
  } else {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('You reached a valid page!');
  }
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000');
});