The following example shows how to render different content based on the user agent in your Edge 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.ts
import { NextResponse, userAgent } from 'next/server';
import type { NextRequest } from 'next/server';
// Set pathname were middleware will be executed
export 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);
}