---
title: Rendering content based on device
description: Learn how to render different content based on the user agent in your Middleware.
url: "https://vercel.com/kb/guide/rendering-content-based-on-device"
published: 2025-11-03
last_updated: 2025-11-11
authors: DX Team
install_vercel_plugin: npx plugins add vercel/vercel-plugin
---

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.

```js
import { NextResponse, userAgent } from 'next/server';

// Set pathname were middleware will be executed
export 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);
}
```
```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);
}
```

## More resources

- [Middleware](/docs/routing-middleware)
  
- [Middleware API](/docs/routing-middleware/api)