Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

287
Views
Rewrites based on the user-agent in nextjs

I have a multi-domain website in NextJs. I want to fetch data based on domain and device type. Now I can recognize the domain but I want to have the user-agent in rewrites rules and use it in the getStaticProps function. Here are my rules 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',
            },
        ],
    };
},

Do you know how to catch user-agent in the rewrite? or do you have any other solution? I want to recognize device types (mobile, tablet, or desktop) and render different DOM based on them.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I solved this issue with the NextJs middleware feature. https://nextjs.org/docs/advanced-features/middleware

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

// RegExp for public files
const PUBLIC_FILE = /\.(.*)$/;

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

    // Skip 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);
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!