Search code examples
javascriptnext.jsmiddleware

How to use Nextjs middleware to redirect users to sub-domain based on IP


I'm trying to figure out how to properly use NextJs's middleware to route users from a specific country to another web domain and I couldn't get it to work properly. Below is my setup:

Main domain: https://www.example.com sub-domain: https://ca.example.com

src/middleware.js

import { NextResponse } from "next/server";

export function middleware(req) {
  const { nextUrl: geo } = req;
  const country = geo.country;
  if (country === "CA") {
    return NextResponse.redirect(new URL(`https://ca.example.com`));
  }
}

The above does not work and I have a feeling that I might have misunderstood how middleware works in my use case. Any pointers would be greatly appreciated!


Solution

  • Ok, I figured it out myself. I've simplified the code and it works now

    import { NextResponse } from "next/server";
    
    export function middleware(req) {
      const country = req.geo.country;
      if (country === "CA") {
        return NextResponse.redirect("https://ca.example.com");
      } else {
        return;
      }
    }