ReactHustle

How to simulate User Country or IP address in NextJS

Jasser Mark Arioste

Jasser Mark Arioste

How to simulate User Country or IP address in NextJS

Hello, hustlers! In this tutorial, you'll learn how to simulate the user's IP address and country. And you'll be able to test your application across different geographic locations.

Why do we need to simulate the IP Address? #

It's widespread in web apps to have a different business logic depending on the geographical location.

How do we implement this in NextJS without relying on 3rd-party proxy services or VPN? These services allow us to simulate the country, but they have limited choices on the free tier. I wanted to be able to remove this restriction so that I could test every possible country on my web app.

The Solution #

Here's how I did it.

In non-production environments, we pass a specific query parameter for the IP Address For example, https://website.com?test_ip=123.146.225.254

Next, create a NextJS middleware to handle the processing of the test_ip so that both the backend and frontend can use it across the entire application. Create a middleware.ts file in your root project directory:

// middleware.ts
import { NextRequest, NextResponse } from "next/server";
const isProduction = process.env.NODE_ENV === "production";
export async function middleware(req: NextRequest) {
  const test_ip = req.nextUrl.searchParams.get("test_ip");
  const res = NextResponse.next();
  if (!isProduction && test_ip) {
    try {
      const response = await fetch(`https://ipapi.co/${test_ip}/country/`);
      const country = await response.text();
      if (country) {
        res.cookies.set("country", country);
      }
    } catch (error) {}
  }
  return res;
}
1234567891011121314151617

Explanation: 

Line 7: We check if the environment is not production and if there's a test_ip we'll use it as the parameter to get the country.

Lines 11-15: We get the country code using https://ipapi.co (You can use any IP service provider that you like) and assign it to a cookie named country. You may now use this cookie for both the backend and frontend.

The good thing about this solution is that you can use this in your local development environment. There are no restrictions to what IP address and countries you can test.

The cookie security is not strict here because we'll only use it for testing purposes. In a real production environment, the provider usually provides the country. Check my previous tutorial How to Get User Country in NextJS and How to Chain Middleware Function in NexJS.

Usage in getServerSideProps #

To get the country in getServerSideProps, first, let's install the cookies npm package to get the cookies more easily.

yarn add cookies && yarn add -D @types/cookies
1

Usage now is very easy, we'll just get the country from the cookie.

import { GetServerSideProps, NextPage } from "next";
import React from "react";
import Cookie from "cookies";
type Props = {
  countryCode?: string;
};
const HomePage: NextPage<Props> = ({ countryCode = "" }) => {
  return (
    <div>
      <h1>Welcome to Simulate IP Tutorial</h1>
      <p>Country: {countryCode}</p>
    </div>
  );
};
export default HomePage;
export const getServerSideProps: GetServerSideProps<Props> = async (ctx) => {
  //req and res already went through the middleware and has the cookie
  const { req, res } = ctx;
  const cookies = new Cookie(req, res);
  const countryCode = cookies.get("test-country");
  return {
    props: {
      countryCode,
    },
  };
};
1234567891011121314151617181920212223242526

Here's a demo when simulating an IP address from Canada:

Next JS Simulate IP Address Canada

Usage in API paths #

Usage in API paths is similar to getServerSideProps:

// pages/api/country
import type { NextApiRequest, NextApiResponse } from "next";
import Cookie from "cookies";
type Data = {
  countryCode?: string;
};
export default function handler(
  req: NextApiRequest,
  res: NextApiResponse<Data>
) {
  const cookies = new Cookie(req, res);
  const countryCode = cookies.get("country");
  res.status(200).json({ countryCode });
}
1234567891011121314

Demo:

NextJS Static Page Country from API

Usage in Static Pages / getStaticProps #

Since the cookie is not HTTP-only, we can also access it in the browser. First, let's install browser-cookies package to parse the cookies more easily:

#yarn
yarn add browser-cookies

#npm
npm i browser-cookies
1234

Inside your static page, you can display the country by reading the cookie:

import React, { useEffect, useState } from "react";
import Cookies from "browser-cookies";
const StaticPage = () => {
  const [country, setCountry] = useState("");
  useEffect(() => {
    setCountry(Cookies.get("country") ?? "");
  }, []);
  return (
    <div>
      <h1>Static Page</h1>
      <p>Country: {country}</p>
    </div>
  );
};
export default StaticPage;
123456789101112131415

Result:

NextJS Static Page Country

Conclusion #

We learned how to simulate user IP and country in NextJS using a combination of Middleware and a 3rd-party IP Service and test it across different geographical locations. 

If you like this tutorial, please leave a like or share this article. For future tutorials like this, please subscribe to our newsletter or follow me on Twitter.

Credits: Image by Julia Schwab from Pixabay

Share this post!

Related Posts

Disclaimer

This content may contain links to products, software and services. Please assume all such links are affiliate links which may result in my earning commissions and fees.
As an Amazon Associate, I earn from qualifying purchases. This means that whenever you buy a product on Amazon from a link on our site, we receive a small percentage of its price at no extra cost to you. This helps us continue to provide valuable content and reviews to you. Thank you for your support!
Donate to ReactHustle