Cookies Psst! Do you accept cookies?

We use cookies to enhance and personalise your experience.
Please accept our cookies. Checkout our Cookie Policy for more information.

Whitelisting URL Paths Using Regular Expressions

In software development, there are times when you need to restrict the execution of certain blocks of code based on the incoming request URL. One common way to achieve this in a web application is by whitelisting specific URL paths using regular expressions (regex).

Why Use Regular Expressions?

By using regex, you can create a pattern that matches a set of URL paths that you want to allow or "whitelist". This approach provides flexibility and allows you to define complex matching criteria for your whitelisted paths.

Creating the Whitelist

To whitelist specific request paths, you'll need to create a regular expression for each path. Once you have all the individual regex patterns, you can merge them into a single regex pattern for better performance.

Here's an example demonstrating how to create a whitelist using a single regex pattern:

/**
 * Regular expression pattern for whitelisting request paths.
 * Each pattern represents an allowed HTTP method and path.
 */
const whiteListedPathsPattern = new RegExp(
  [
    `^GET /api/user$`,
    `^POST /api/app//products/search$`,
    `^POST /api/app/uninstall$`,
    `^POST /api/app/disconnect$`,
    `^GET /api/app/complaince/[a-z_]*$`,
    `^POST /api/notification/brand$`,
  ].join('|')
);

const incomingRequestUrl = 'URL_HERE';

if (whiteListedPathsPattern.test(incomingRequestUrl)) {
    // Execute your code block
    console.log('Request is whitelisted. Proceeding with the execution...');
} else {
    // Handle unauthorized request
    console.log('Request is not whitelisted. Access denied.');
}

 Complete Express.js Example

For a comprehensive example demonstrating how to implement this in an Express.js application, check out this GitHub Gist.

Last Stories

What's your thoughts?

Please Register or Login to your account to be able to submit your comment.