Prevent Website Spoofing in Next.js App

Prevent Website Spoofing in Next.js App

Divyajyoti Ukirde's photo
Divyajyoti Ukirde
·May 11, 2022·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

This is a mechanism to secure your web application from running on a different host. Running your application on a different host 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.

You can directly jump down to Secure your Nextjs App section to see the code.

Let's try to simulate this scenario.

Open your terminal.

$ ping

Copy the IP address -

Go to 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.
##       localhost broadcasthost
::1             localhost

Now open on your browser. You should see the same content as site. If you look at the headers, it shows the same remote address.
Screenshot 2022-05-11 at 1 59 48 PM
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.

Secure your Nextjs App

Now, let’s write a way to prevent this in our Nextjs App. We will write a code that will check the host from request headers and redirect to our application if the domain is not whitelisted. So, if requests app, should not let access.

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 =;
    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;

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

  return appProps;

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

Originally wriiten here -

Share this