Rewrites based on the user-agent in nextjs

Viewed 510

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.

1 Answers

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