How to block traffic from a specific list of IP addresses?

I’d like to block traffic from a specific set of IP addresses. What’s the best way to do that?

1 Like

You can use CDN-as-JavaScript and the x-xdn-client-ip header to block specific IP addresses. An example of blocking all traffic except specific IP addresses is in the cookbook.

If you will be doing this frequently, you can specify the IP addresses to block in an environment variable. This will allow you to manipulate the list of IP addresses to block without having to make a code change.

Here’s an example router.js file that does this:

// This file was automatically added by xdn deploy.
// You should commit this file to source control.
import { Router } from '@xdn/core/router'
import { nextRoutes } from '@xdn/next'

const router = new Router();

// Checked if there are blocked IP addresses
// 'BLOCKED_IPS' is an environment variable that contains a regular expression 
// to match IPs addresses that should be blocked, e.g. to block IP addresses
// and then set the variable to the following value in
// the XDN console:
// 'BLOCKED_IPS' == 24\.16\.45\.116|128\.1\.1\.16
const blockedIPs = process.env['BLOCKED_IPS'];
if(blockedIPs) {
      headers: {
        // Based on
        'x-xdn-client-ip': new RegExp(blockedIPs),
    ({ send }) => {
      send('Blocked', 403)

// Regular Next.js router
router.match('/service-worker.js', ({ serviceWorker }) => {
  return serviceWorker('.next/static/service-worker.js')
.use(nextRoutes) // automatically adds routes for all files under /pages

export default router; 

Then you would configure the list of IPs to block in your environment variables as shown in the image below. Note that the list of environment variables is a regular expression so you’ll need to escape the period characters and separate each IP address with a | character.

1 Like