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

Copy the IP address -

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

Now open in 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 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 requests app, should not let 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 =;
    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).

Divyajyoti Ukirde

Divyajyoti Ukirde

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