Router

The server's router is responsible for directing each incoming request to the appropriate handler. Static files, such as images or icons, are served automatically without involving the router process. The router is primarily used for routing requests to web pages or API endpoints.

Router Middleware

Some routes are disallowed in the robots.txt file, meaning they will not be indexed by search engines. This is usually because these routes require developers to log in or because the endpoints are API-related.

The router middleware performs several important functions:

Checking Disallowed Routes

  • The router identifies routes disallowed by robots.txt.
  • When a developer tries to access these routes without a valid login session cookie, they are redirected to the authentication page.

Excluding Certain API Endpoints

  • Certain API endpoints are excluded from this redirection and can be accessed without a session cookie.

Sanitizing Request Parameters

  • The middleware sanitizes request parameters (body, query, params) to prevent XSS (Cross-Site Scripting) attacks.

Additional processes may occur within the middleware, but these are not necessary to document here.

Registering Routes

The router reads all routes and API endpoints from this directory and registers them with the HTTP server. The directory contains specific handlers for each route. Here's how the process works:

Route Registration

  • The router parses the directory to identify all routes and their corresponding handlers.
  • Each request to a registered route is directed to its specific handler.

Router Functionality

  • For web page requests, the router uses the EJS SSR (Server-Side Rendering) engine to render parts of the page before sending the content to the client.
  • For API requests, the router processes the request and sends an appropriate response.

Handling Invalid Endpoints

  • Any requests to invalid endpoints are automatically redirected to the home page.

By structuring the router and its middleware in this way, the server ensures secure, efficient, and organized handling of all incoming requests.