Guide on utilizing Nextjs middleware for directing users to sub-domain according to their IP address

I've been struggling to effectively implement NextJs's middleware for redirecting users from a specific country to another web domain. I've encountered some issues with my setup:

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

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 approach hasn't yielded the desired results, and I suspect that my understanding of how middleware works in this context may be flawed. Any insights or guidance on this matter would be greatly welcomed!

Answer №1

After some experimentation, I managed to solve the issue on my own. By simplifying the code, I was able to get it working perfectly

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Removing a specific item from an array

state = { filters: ['all'] } this.state.filters.includes('humans') ? this.state.filters.filter(val => val !== 'humans') : this.state.filters.push(dropdown) I have a condition set up so that when I click on a button, ...

Tips for resizing a 100% div without displaying vertical scrollbars in the browser

I am facing an issue with a table that has three rows. I have a main #container div with a height of 100%, and inside it is a table with 3 rows. The first and last row contain fixed size content. However, in the second row, there is a #content div with a h ...

What is the best way to avoid having identical entries in a row when using jQuery's multiple select feature?

I am facing the challenge of working with multiple rows containing select boxes that have similar content. Each row has several select boxes and each item in a row can only be used once due to specific classifications assigned to each column. I want the se ...

Omit certain components from the JQuery ListNav plugin

I recently incorporated the Jquery plugin for record filtration. I obtained this plugin from the following link: After successfully implementing the plugin, I encountered an issue where it was counting the headings along with the alphabet filters in my co ...

Error when redirecting in Express due to invalid integer input syntax

After executing a PUT query in Postgres through Express, I encountered the following error message: Error: invalid input syntax for integer: "all-calls" This issue seems to be related to the line of code within the router.put function that says response. ...

Menu rollout problem when clicking or hovering

I'm facing challenges in making my menu content appear when a user clicks or hovers over the hamburger menu. My app is built using Angular, and I've written some inline JavaScript and CSS to achieve this, but the results are not as expected. Here ...

I'm having trouble locating the corresponding end tag for "<%". How can I resolve this issue?

Here lies the issue: <% for(let i = 0; i < <%= elements %>.length; i++){ %> <li><%= elements[i] %></li> <%}%> ...

Extracting server error messages on the client side using Node.js

Before storing data in the database, my server performs validation checks. If it is unable to save the data into the database, an error message is sent. In my client-side application, how can I retrieve and display this error message? Below is the HTTP r ...

How can we enable a sitemap for web crawlers in a nodejs/express application?

Looking to enable sitemap for web crawlers in nodejs/express? I am trying to figure out where I should place my sitemap folder/files within the application flow and how to allow access for web crawlers. Currently, when visiting domain/sitemap/sitemap.xml, ...

Node.js promises are often throwing Unhandled Promise Rejection errors, but it appears that they are being managed correctly

Despite my efforts to handle all cases, I am encountering an UNhandledPromiseRejection error in my code. The issue seems to arise in the flow from profileRoutes to Controller to Utils. Within profileRoutes.js router.get('/:username', async (r, s ...

Struggling with setting up Chrome options using Selenium WebDriver in JavaScript?

Encountering an issue while attempting to access a specific website using Selenium WebDriver in JavaScript with the Chrome browser. In the provided code snippet, the browser driver is initialized; however, there seems to be a problem when utilizing setChro ...

Secure Cookie Configuration with Node Http Module and IIS

Currently, my focus is on implementing secure flagged cookies within a node app running on IIS. I'm currently developing a Next.js application and attempting to deploy it on IIS to fulfill certain corporate requirements. In order to achieve this, I h ...

Navigate through a filtered list of parent items with the use of cursor arrows in AngularJS

My form contains an input with a dropdown, where I display JSON data like this: { "title": "Parent #1", "child" : [ {"title": "Child ##1"}, {"title": "Child ##2"}, {"title": "Child ##3"}, {"title": "Child ##4"} ...

Using tokens to make consecutive API calls in JavaScript/Node.js

After generating the token, I need to make sequential calls to 5 different APIs. The first API used to generate the token is: POST https://idcs-xxxx.identity.c9dev2.oc9qadev.com/oauth2/v1/token Using the username and password, I will obtain the token from ...

How can I fetch data in NextJS after a click event occurs?

I'm facing an issue when trying to load data into a component after clicking on a button. Currently, I am using the getInitialProps method to initially load the data on the page. Is there a way to load new data and pass it to the {data} variable aft ...

Tips for interpreting the JSON data returned by a Node server in Angular

When trying to implement a login form in my Angular frontend, I encountered an issue with reading the JSON object returned from my node.js server. Despite following the correct steps, the console displays "undefined" as if it cannot recognize the format. ...

How can you trigger a 'hashchange' event regardless of whether the hash is the same or different?

Having a challenge with my event listener setup: window.addEventListener('hashchange', () => setTimeout(() => this.handleHashChange(), 0)); Within the handleHashChange function, I implemented logic for scrolling to an on-page element whil ...

What is the best way to ensure my php variable is easily accessed?

Recently, I've been working on implementing a timer and came across the idea in a post on Stack Overflow. <?php if(($_SERVER['REQUEST_METHOD'] === 'POST') && !empty($_POST['username'])) { //secondsDif ...

What is the reason behind allowing JavaScript to perform mathematical operations with a string type number?

let firstNum = 10; let secondNum = "10"; console.log(firstNum * secondNum); // Result: 100 console.log(secondNum * secondNum); // Result: 100 ...

Guide to sending an ajax request from one page and receiving the response on a different page

Looking for advice on sending Ajax requests using jQuery and HTML5. I have multiple pages within my application. Is it possible to send an Ajax request from one page (e.g sync.html) and receive a response on another page (e.g home.html)? I am aware of alte ...