create a url router with regex in javascript

In JavaScript, we can create a URL router using regular expressions (regex). This is useful when we want to map different URL patterns to specific functions, handlers or controllers. Here's an example of how to create a simple router using Node.js:

index.tsx
const http = require('http');

const PORT = 3000;

const routes = {
  '/': homeHandler,
  '/about': aboutHandler,
  '/products/:id': productsHandler,
  '/*': notFoundHandler
}

function homeHandler(req, res) {
  res.write('Welcome to the homepage');
  res.end();
}

function aboutHandler(req, res) {
  res.write('This is the About page');
  res.end();
}

function productsHandler(req, res, {id}) {
  res.write(`Product page for ID: ${id}`);
  res.end();
}

function notFoundHandler(req, res) {
  res.write('404 Page Not Found');
  res.end();
}

const server = http.createServer((req, res) => {
  const { url } = req;
  const keys = Object.keys(routes);
  
  for (const key of keys) {
    const pattern = new RegExp(`^${key.replace(/:\w+/g, '(\\w+)')}$`);
    const match = url.match(pattern);
    
    if (match) {
      const [, ...values] = match;
      const params = {};
      
      key.split('/').forEach((segment, index) => {
        if (segment.startsWith(':')) {
          params[segment.slice(1)] = values[index];
        }
      });
      
      req.params = params;
      return routes[key](req, res, params);
    }
  }
  
  return routes['/*'](req, res);
});

server.listen(PORT, () => {
  console.log(`Server listening at http://localhost:${PORT}`);
});
1268 chars
61 lines

This router uses an object called routes to map different URL patterns to specific handler functions. The /* route is a catch-all for any other URLs that don't match any of the other patterns.

The router uses a regular expression to match the URL pattern with the incoming request URL. The expression replaces any :param segments in the route with a regex match for one or more word characters. This allows us to extract the value of any parameter segments in the URL.

The router also uses the req.params object to extract any parameter values and pass them to the corresponding handler function. This makes it easy to access and use parameter values in the handler.

With this router, you can easily create more handlers for other URL patterns by adding to the routes object.

gistlibby LogSnag