2

How can I grant access for only mobile devices can access to middleware in nextjs ? Because I want to handle some DOMs for a webview app, for desktop web, I want it to directly go to index page without go through middleware.

I'm using Next version 13.

Please help me !

MinhDat
  • 57
  • 3

2 Answers2

3

you can look for sec-ch-ua-mobile in request headers to check if request is being made form mobile device or Not

check this for more detailed explaination: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Sec-CH-UA-Mobile

import { NextResponse } from 'next/server'

export function middleware(request) {
  console.log('headers: ', request.headers)
  /* Console
    headers: {
      ...
      sec-ch-ua-mobile: '?0', // this is the key with which you can determine if request is form mobile or desktop, `?1` indicates true and `?0` being false
      sec-ch-ua-platform: '"Windows"',
      ...
    }
   */
  if (request.headers.get('sec-ch-ua-mobile') === '?1'){
    // do something for requests with mobile device
  }

  return NextResponse.next();
}

export const config = {
  matcher: ['/((?!api|_next/static|_next/image|favicon.ico|images|design).*)'],
}
sterling
  • 70
  • 3
2

Two potential solutions, although neither is perfect:

  1. User-Agent sniffing in Next middleware:
export function middleware(request) {
  const userAgent = req.headers['user-agent']

  // example regex -- tweak for your use case
  const isMobile = /(iPhone|iPad|Android)/i.test(userAgent);

  if (isMobile) { ... }
}
 
  1. Adding an ?isMobile parameter to your GET request. This assumes you control the client app as well:
export function middleware(request) {
  const url = new URL(request.url, "http://blah.com"); // base URL doesn't matter

  const isMobile = url.searchParams.get("isMobile") === "true";

  if (isMobile) { ... }
}
pppccc
  • 46
  • 3