---
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)

## More Routing Middleware guides

- [How can I increase the limit of redirects or use dynamic redirects on Vercel?](/kb/guide/how-can-i-increase-the-limit-of-redirects-or-use-dynamic-redirects-on-vercel): Instructions on how to use Serverless Functions to handle redirects on Vercel.
- [How to Optimize Next.js + Sitecore JSS](/kb/guide/how-to-optimize-next.js-sitecore-jss): This guide covers performance and usage considerations when building and deploying your Next.js and Sitecore JSS application.
- [Dynamic redirects with Global Config and Next.js proxy](/kb/guide/dynamic-redirects-with-global-config-and-next-js-proxy): Learn how to create redirects that update instantly without redeploying by storing rules in Global Config and reading them from your Next.js proxy.