Prevent Website Spoofing in Next.js App

This post will discuss on how to secure your web application from running on a different domain. Running your application on an unknown/hostile domain may lead to security issues like leaking of user information, requesting servers other than your server, and a lot more which is not in the scope of this article. Concisely speaking, this is to prevent website spoofing.

Let's try to simulate this scenario.

Open the terminal and get the IP address of a domain:

$ ping ecbiz312.inmotionhosting.com

Copy the IP address - 209.182.215.63

Open your hosts file:

// in macOS
$ sudo vim /etc/hosts

And make changes as below:

##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
##
127.0.0.1       localhost
209.182.215.63  mywebsite.xyz
255.255.255.255 broadcasthost
::1             localhost
~
~

Now open mywebsite.xyz in your browser. You should see the same content as ecbiz312.inmotionhosting.com site. If you look at the headers, it shows the same remote address.

Screenshot 2022-05-11 at 1 59 54 PM
Screenshot 2022-05-11 at 2 00 55 PM
Screenshot 2022-05-11 at 2 00 36 PM

It is completely fine if you are not able to simulate this on your machine.

Securing the Next.js App

Now, let’s discuss how to prevent it in our Next.js App. We will write a code that will check the host from request headers and redirect if the domain is not whitelisted. So, if mywebsite.xyz requests ecbiz312.inmotionhosting.com app, ecbiz312.inmotionhosting.com should not let mywebsite.xyz access the app.

In your _app.js file:

import App from 'next/app'

MyApp.getInitialProps = async ( appContext ) => {
  const appProps = await App.getInitialProps(appContext);
  const req = appContext.ctx.req;
  const res = appContext.ctx.res;
  if ( req ) {
    const headers = req.headers;
    const host = headers.host;
    const whiteList = [“your”,”whitelisted”, “domains”];
    let len = whiteList.length;
    let isInvalidHost = true;
    while( len-- ) {
      let thisWhiteListDomain = whiteList[ len ];
      thisWhiteListDomain = thisWhiteListDomain.replace("https://", "");
      if ( host === thisWhiteListDomain ) {
        isInvalidHost = false;
        break;
      }
    }

    if ( res && isInvalidHost ) {
      res.writeHead(301, {
        Location: 'https://your-application-domain'
      });
      res.end();
    }
  }

  return appProps;
};

So, if another domain tries to request our application, we redirect the user with 301(permanent redirect - good for SEO).

Divyajyoti Ukirde

Divyajyoti Ukirde

Senior Software Engineer | Investing in knowledge | with Passion for building stuff