繁体   English   中英

基于 nextjs 中的用户代理重写

[英]Rewrites based on the user-agent in nextjs

我在 NextJs 中有一个多域网站。 我想根据域和设备类型获取数据。 现在我可以识别域,但我想让用户代理重写规则并在 getStaticProps 函数中使用它。 这是我在 next.config.js 文件中的规则。

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

你知道如何在重写中捕获用户代理吗? 还是您有其他解决方案? 我想识别设备类型(移动设备、平板电脑或桌面设备)并根据它们呈现不同的 DOM。

我用 NextJs 中间件功能解决了这个问题。 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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM