Enhancing user experience by tailoring rewrites in Next.js according to the user-agent

I am working on a NextJs multi-domain website and need to fetch data based on the domain and device type. While I am able to identify the domain, I am looking to extract the user-agent in rewrite rules and utilize it within the getStaticProps function. Below are the rewrite rules specified in the next.config.js file.

async rewrites() {
    return {
        afterFiles: [
            {
                has: [
                    {
                        type: 'host',
                        value: '(?<host>.*)',
                    },
                    {
                        type: 'header',
                        key: 'User-Agent',
                        value: '(?<ua>.*)',
                    },
                ],
                source: '/',
                destination: '/organizations/:host?ua=:ua',
            },
        ],
    };
},

Is there a way to capture the user-agent in the rewrite process, or do you have any alternative approach in mind? My goal is to differentiate between device types (mobile, tablet, or desktop) and dynamically render different content based on this information.

Answer №1

The solution to my problem was found by utilizing the middleware feature in NextJs. For more information, you can visit https://nextjs.org/docs/advanced-features/middleware

import { NextRequest, NextResponse } from 'next/server';
import parser from 'ua-parser-js';

// Regular expression for identifying public files
const PUBLIC_FILE = /\.(.*)$/;

export async function middleware(req: NextRequest) {
    // Clone the URL
    const url = req.nextUrl.clone();

    // Exclude public files
    if (PUBLIC_FILE.test(url.pathname)) return;

    const ua = parser(req.headers.get('user-agent')!);
    const viewport = ua.device.type === 'mobile' ? 'mobile' : 'desktop';

    url.pathname = `/${viewport}/${req.headers.get('host')}${url.pathname}`;

    return NextResponse.rewrite(url);
}

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 is the most efficient way to calculate the current percentage of time that has elapsed today

Is there a way to calculate the current time elapsed percentage of today's time using either JavaScript or PHP? Any tips on how to achieve this? ...

"Exploring the versatility of using variables in jquery's .css

I’m facing an issue where I need the rotation of a div to be based on the value stored in "anVar." This is what I currently have: function something() { $('.class').css('-webkit-transform:rotate('anVar'deg)') } The desi ...

Effective ways to modify the Next-pwa caching strategy

Currently, I am attempting to modify the caching strategy of the Next-Pwa plugin from NetworkOnly to CacheFirst for data retrieval. https://i.stack.imgur.com/6o2Wf.png The image shows that it is currently using NetworkOnly for fetching incoming data. I ...

Redux - Preventing Overwriting of Product Quantity in Cart by Creating a New Object

Is there a way to address the issue where adding the same product multiple times to the cart creates new objects instead of increasing the quantity? switch (action.type) { case actionTypes.ADD_TO_CART: const product = state.products.find((p) = ...

AG Grid Community styles may fail to load correctly in a Next.js production build, requiring a page refresh for them

Encountering a challenge with AG Grid Community version integrated into a Next.js application. Upon navigating to the grid page in production, the grid styles fail to load correctly. However, after manually refreshing the page, the styles display as expect ...

Troubleshooting Datatables and ASP.net - The mysterious HTTP Error 404.15 that leaves you lost and

When making a request with datatables, I am encountering an issue with the URL being too long. The current URL is as follows: http://localhost:12527/MyHandler.ashx?draw=1&columns%5B0%5D%5Bdata%5D=0&columns%5B0%5D%5Bname%5D=&columns%5B0%5D%5Bse ...

React and Next.js issues with "Window is not defined" errors

Currently working with React Hooks and NextJS, I am in the process of creating a Navbar along with its functionality. However, upon refreshing the page, an error appears that was not present when I was using this code in my previous React project. If anyo ...

Improve the Popup to seamlessly elevate

In my project, I have implemented a pop-up dialog box that rises up from the left bottom corner as the user scrolls down the page. You can view it live at this link- However, I am facing an issue where the initial lift up of the dialog box is not smooth, ...

Tips for ensuring that the horizontal scroll bar remains consistently positioned at the bottom of the screen

There are two div sections on a page, with one positioned on the left and the other on the right. The div on the right contains multiple dynamically generated tags which necessitate a horizontal scroll bar (overflow:auto). This causes the div's height ...

Attempting to alert a particular device using Flutter for notification delivery

Currently, I am developing a Chat app using Flutter and attempting to send notifications to specific devices through Firebase functions. Initially, I retrieve the device token and store it in Firebase. Now, my challenge lies in fetching the token and invok ...

Something is wrong with the conditional compilation in the JavaScript code

I encountered a "Conditional compilation is turned off" error in my JavaScript code. How can I resolve this issue? var <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="176264726559767a722a6765727a763976397679747f786557626739786 ...

I am encountering an issue with the useRef function not properly detecting visibility

I'm looking to incorporate a fade-in animation into my React div as I scroll and reach a specific section. Unfortunately, the useEffect function that is supposed to detect the scrolling behavior seems to be malfunctioning and I can't figure out w ...

How can I dynamically display Material-UI's <MenuItem/> within a <DropDownMenu/> using ReactJS?

In my ReactJS + Material-UI project, I am working with an array named colors that contains different color strings such as "white", "blue", and "green. My goal is to render each color string as a <MenuItem/> within a <DropDownMenu/> component ( ...

The Jssor bullet navigator is not visible on the webpage

Currently, I am working on implementing a full-width slider with arrow navigators, bullet navigators, and captions using the Jssor plugin. Rather than copying and pasting example code, I decided to tackle this project independently with just a little guida ...

The challenge of accessing controllerAs variables/objects in AngularJS custom directives

After deciding to refactor my code and move DOM manipulation and functions into directives instead of controllers, I encountered an issue with accessing variables/objects defined using the controllerAs 'this' syntax. Despite trying to use bindToC ...

What could be causing the error 404 message to appear when trying to retrieve video data?

I'm having trouble displaying a video in mp4 format from the code's folder. When I attempt to fetch the video by clicking on the button, it shows an empty space instead of displaying the video. Here is an example of what the output looks like. T ...

Placing jQuery scripts in Blogger platform: A guide

After finding the correct codes to solve my problem in previous questions, such as How do I get an image to fade in and out on a scroll using jQuery?, I came across this helpful code snippet: var divs = $('.banner'); $(window).scroll(function(){ ...

Is it necessary to incorporate Babel into a project that involves developing a backend service using Node.js and a front-end component using the EJS view engine?

I find myself a little confused. Some say that if you are working on pure Node.js projects, there is no need to stress about this issue. However, for web development, it's important to be familiar with these tools. On the other hand, some recommend us ...

Reset all divs to their default state except for the one that is currently active using jQuery

Here's the plan for my script: Once a user clicks on a "learn more" button, it will reveal the relevant information in the corresponding box. I'm aiming to implement a feature where if you click on another "learn more" button while one box is a ...

What is the best way to increase incremental values that are nested within each other

A database has been loosely created with a key known as website. Inside this website object, multiple objects exist, one for each dynamically generated website. An illustration of how the database might appear is shown below: website: { google.com: { ...