基于用户代理的Next.js重写

3

我在 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。


我想在重写规则中获取用户代理,并在 getStaticProps 函数中使用它。getStaticProps构建时 在服务器上运行。您无法在其中访问请求特定信息,如标题或用户代理。 - juliomalves
谢谢您的回复。我知道这一点,但我想要预测它。例如,在构建时生成我的页面的两个版本(移动版和桌面版),然后在运行时根据请求选择适当的构建器页面。我对主机采用这种策略(我有几个组织拥有单独的域名)。 - elyas.m
我理解了,好的。根据上述规则,用户代理是否不会添加为查询字符串,或者重写根本不会发生? - juliomalves
在查询参数中,我有主机值和用户代理未包含。 - elyas.m
你的问题刚好解决了我基于主机的静态生成问题,谢谢 @elyas.m :) - ΔO 'delta zero'
显示剩余2条评论
1个回答

1
我使用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);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接