Attempting to modify text using the header parameter has proven to be ineffective

pages/_middleware.ts

import { NextRequest, NextResponse } from 'next/server';

const isMobile = (userAgent: string) =>
  /iPhone|iPad|iPod|Android/i.test(userAgent);

const propName = 'x-rewrite';

enum Device {
  desktop = 'no',
  mobile = 'yes',
}

export function middleware(req: NextRequest) {
  const userAgent = req.headers.get('user-agent');

  const res = NextResponse.next();

  if (userAgent) {
    if (isMobile(userAgent)) {
      res.headers.set(propName, Device.mobile);
      console.log(res.headers, 'res');
      return res;
    } else {
      res.headers.set(propName, Device.desktop);
      return res;
    }
  }
}

next.config.js

async rewrites() {
    return {
      beforeFiles: [
        {
          source: '/football/livescore',
          destination: '/football/livescore/mobile',
          has: [
            {
              type: 'header',
              key: 'x-rewrite',
              value: '(?<rewrite>yes|true)',
            },
          ],
        },
        {
          source: '/football/livescore/:league',
          destination: '/football/livescore/mobile/:league',
          has: [
            {
              type: 'header',
              key: 'x-rewrite',
              value: '(?<rewrite>yes|true)',
            },
          ],
        },
      ],
    };
  },

https://github.com/vercel/next.js/discussions/37841 here, I've started a discussion to address an issue regarding rewriting pages by using the header type in my project. Despite setting the value in headers and checking them in the browser, it doesn't seem to work as expected.

Answer №1

Instead of the traditional approach of setting the header in middleware and using rewrites in next.config.js, you have the option to directly rewrite to the mobile path by utilizing NextResponse.rewrite within the middleware itself.

import { NextRequest, NextResponse } from 'next/server';

const livescorePath = '/football/livescore';
const mobilePath = '/mobile'

const isMobile = (userAgent: string) => /iPhone|iPad|iPod|Android/i.test(userAgent);

export function middleware(req: NextRequest) {
    const { pathname } = req.nextUrl;
    const userAgent = req.ua?.ua ?? '';

    // Conditionally rewrite to the mobile path if the path starts with `/football/livescore` and has a mobile user agent
    if (pathname.startsWith(livescorePath) && !pathname.includes(mobilePath) && isMobile(userAgent)) {
        const league = pathname.replace(livescorePath, '');
        req.nextUrl.pathname = `${livescorePath}${mobilePath}${league}`;
        return NextResponse.rewrite(req.nextUrl);
    }

    return NextResponse.next();
}

Answer №2

import { NextRequest, NextResponse } from 'next/server';

const checkIfMobile = (userAgent: string) =>
  /iPhone|iPad|iPod|Android/i.test(userAgent);

export function middleware(req: NextRequest) {
  const userAgent = req.headers.get('user-agent');
  const { pathname, origin } = req.nextUrl;

  if (userAgent && !pathname.includes('favicon.ico')) {
    if (checkIfMobile(userAgent)) {
      return NextResponse.rewrite(`${origin}/mobile${pathname}`);
    } else {
      return NextResponse.rewrite(`${origin}/desktop${pathname}`);
    }
  }
}

Here is the suggested folder structure:

pages/mobile pages/desktop

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

What could be the reason behind encountering an NaN error while using these particular functions?

I recently delved into the world of JavaScript, starting my learning journey about two months ago. While going through a few tutorials, I stumbled upon an intriguing project idea. However, I've hit a roadblock that's impeding my progress. Every t ...

My objective is to show the div element just once using AngularJS

Here's the scenario I want to show this div just once, not multiple times: //angular js code $scope.arr=["sunday","mpnday","tuesday"]; //html view <ul> <li ng-repeat="x in arr"> <div><p>{{ x }}</p> </div> & ...

I am encountering an issue with my Javascript file not running due to a bigint error

I'm attempting to utilize @metaplex/js for NFT minting. Usually, my .js files function correctly, but when I execute the file, this particular error arises. bigint: Failed to load bindings, pure JS will be used (try npm run rebuild?) The meaning of ...

'The error thrown states: "ReferenceError: httpResponse is not defined" occurs while attempting to parse the JSON response from a Parse HTTP

My commitment statement involves sending multiple requests to eBay, each time using the properties of a matchCenterItem as parameters. Once all instances have been processed, I aim to transmit all the responses to my iOS application. However, my effort to ...

The issue of passing a local object from ng-repeat into a directive controller remains unresolved

I'm struggling to pass my local object from ng-repeat to a directive. My goal is to access the data from that object within the controller of the directive. The confusion arises with how the isolated scope and controller scope interact. I can't f ...

Issues with recurring prices in Stripe checkout are causing errors in NextJS and React

After attempting to integrate a Stripe checkout into my NextJS application, I encountered an error message that has left me puzzled. The specific error states: "You specified payment mode but passed a recurring price. Either switch to subscription mode o ...

Tips for launching a Next.js application on cPanel

These were the steps I took to successfully deploy my nextjs on cPanel: First, I added this line to package.json: "homepage": "http://afsanefadaei.ir" Next, I ran next build to generate the .next folder as my build directory I then navigated to cpa ...

Pattern to prevent consecutive hyphens and identical digits next to one another in a series

Here is a regular expression that can validate all numbers not being the same even after a hyphen: ^(\d)(?!\1+$)\d{3}-\d{1}$ For example, in the pattern: 0000-0 would not be allowed (all digits are the same) 0000-1 would be allowed 111 ...

Using a single package manager for both backend and frontend development - is it possible? (Yarn/NPM)

Before, I relied on NPM for server-side tasks and Bower for frontend. NPM would install packages in the node_modules/ directory, while a .bowerrc file directed package installations to public/lib. Recently, I've made the switch to Yarn from NPM, and ...

Implementing styling upon app mounting in Vue.js - a step-by-step guide

Hey, I'm working with a template code that looks like this: Here's my script code: data () { return { loadPage: true } }, mounted () { this.loadPage = true }, And here is my styling code: #app{ width: 100%; opacit ...

Angular 7+: Trouble with displaying images from assets directory

Details regarding my Angular version: Angular CLI: 7.3.9 Node: 10.15.3 OS: win32 x64 Angular: 7.2.15 ... animations, common, compiler, compiler-cli, core, forms ... language-service, platform-browser, platform-browser-dynamic ... rout ...

A notification appears when the record is being inserted after clicking the button

Just venturing into the PHP and MYSQL realm, so please excuse any beginner questions. Before I submit data from a form to my SQL table, I'd like to display a confirmation POP UP message asking "Are you sure you want to insert this data?" ...

Do iframes not utilize parental jquery?

I have a homepage that utilizes jQuery by loading it from the ajax google APIs in the head> tag. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.js" type="text/javascript"></script> I attempted to use jQuery functions ...

Error: Invalid hook calls detected in React using Material-UI components

Hey there! I'm relatively new to the world of React and I've been tackling an issue with implementing the SimpleBottomNavigation component. Unfortunately, I keep running into an error message that says: "Uncaught Error: Invalid hook call. Ho ...

Alter the entity type when passing it as a parameter

Trying to alter the Entity type, I am invoking a function that requires two parameters - one being the entity and the other a location. However, when trying to assign a Type for the first entity, it throws an error: Error: Argument of type 'Node<En ...

Ways to sum up the values within a JSON object

Currently, I am using an AJAX call to fetch JSON data from an API. My goal now is to add up all the visits. This is what I have implemented so far. Any suggestions on how I can achieve that? $(document).ready(function() { var X = []; var Y = []; var d ...

Exploring IP geolocation integration within Rails 3

I am looking to add a dynamic feature to my homepage that will display the location object closest to the reader's physical location. Currently, I have a Location model with longitude and latitude fields. My goal is to retrieve the location model obj ...

Trouble arises when attempting to append a class through ng-class upon clicking

In a specific scenario, I am trying to change the border color from black to red in a div by appending a class using ng-class when clicked. However, when clicking a button, the modal opens but the class is not being appended as expected. <div ng-class ...

Unveiling concealed content with JQuery

Here is a link to my pen: http://codepen.io/anon/pen/IszKj I am looking to achieve the functionality where clicking on either "any status" or "any date" will reveal a hidden div containing a list of options. My main query is about the best approach to ta ...

Is there a way to adjust React states directly in the browser without relying on React dev tools?

Recently, my website was compromised and an individual was able to manipulate the react states, gaining access to sensitive information such as an admin panel. In addition, they were able to alter the userID within the useState function, resulting in a co ...