The following example shows how to render different content based on the user agent in your Middleware.
Your middleware file should be placed at the root of your project. If you are using the src directory, the file should be placed in the src directory.
middleware.js
import { NextResponse, userAgent } from 'next/server';
// Set pathname were middleware will be executedexport const config = { matcher: '/',};
export default function middleware(request) { // Parse user agent const { device } = userAgent(request);
// Check the viewport const viewport = device.type === 'mobile' ? 'mobile' : 'desktop';
// Update the expected url request.nextUrl.pathname = `_viewport/${viewport}`;
// Return rewritten response return NextResponse.rewrite(request.nextUrl);}middleware.ts
import { NextResponse, userAgent } from 'next/server';import type { NextRequest } from 'next/server';
// Set pathname were middleware will be executedexport const config = { matcher: '/',};
export default function middleware(request: NextRequest) { // Parse user agent const { device } = userAgent(request);
// Check the viewport const viewport = device.type === 'mobile' ? 'mobile' : 'desktop';
// Update the expected url request.nextUrl.pathname = `_viewport/${viewport}`;
// Return rewritten response return NextResponse.rewrite(req.nextUrl);}