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.