The process of setting permissions for a webview app to only access a middleware in next.js

Is there a way to restrict access to middleware in Next.js so that only mobile devices can access it? I need to handle certain DOM elements for a webview app, but for desktop web, I want them to go directly to the index page without passing through the middleware. Currently using Next version 13.

Your assistance is greatly appreciated!

Answer №1

To determine whether a request is being made from a mobile device or not, you can check for the presence of sec-ch-ua-mobile in the request headers.

For a more detailed explanation, please refer to: 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 key indicates if the request is from a mobile (`?1` denotes true and `?0` denotes false)
      sec-ch-ua-platform: '"Windows"',
      ...
    }
   */
  if (request.headers.get('sec-ch-ua-mobile') === '?1'){
    // Perform actions specific to requests from mobile devices
  }

  return NextResponse.next();
}

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

Answer №2

Two potential solutions, although neither is ideal:

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

  // example regex -- customize for your specific needs
  const isMobile = /(iPhone|iPad|Android)/i.test(userAgent);

  if (isMobile) { ... }
}
 
  1. Include an ?isMobile parameter in your GET request. This assumes you have control over the client app:
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) { ... }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

After reloading the page, the Next JS code in getInitialProps does not run as expected

While integrating NextJS into my React app, I encountered a problem. When the page is reloaded or accessed directly via a link (e.g., somehostname.com/clients), my getInitialProps function does not execute. However, if I navigate to the page using <Link ...

OneGraph and Graphql Codegen produce enums with numerical representations

After migrating my project's codebase from using the direct Headless Wordpress GraphQL endpoint to OneGraph for Google+Facebook Business support, I encountered an error related to apollo referencing the output codegen. Here is the specific error messa ...

The issue with Google Maps not functioning properly at 100vh has been identified specifically on Android app

#map-canvas {height: 100vh; width: 100vw;} <ion-view title="Truck Map"> <ion-nav-buttons side="left"> <button menu-toggle="left" class="button button-icon icon ion-navicon"></button> </ion-nav-buttons> < ...

Do you think the Service Worker setup poses a potential risk?

Currently, I am immersed in the development of an e-commerce platform using Next JS. One major issue plaguing the website is its slow page load speed, largely attributed to the multitude of third-party vendors whose JavaScript files cannot be removed. To a ...

What could be causing the error to originate from a different component?

I recently developed a Next.js application that features two distinct navbars, with one dedicated to the home page and the other for all other routes. In my header.js file, I have the following code snippet: import React, { useEffect, useState } from " ...

Obtain a file from extracting data from a JSON object generated by querying a

I am looking to display data from MySQL in a recyclerview, which includes PDF files. Additionally, I would like users to be able to download these PDF files along with performing data manipulation. ...

What is the best way to access an API located in a different pod within the same Kubernetes development cluster and namespace from a NextJS pod?

Incorporating a NextJS app into our namespace's dev cluster has been a smooth process. When running Kubectl get all --namespace [my-namespace], the following information is returned: NAME READY STATUS RESTAR ...

When integrating Framer-motion with NextJS (v13.x.x), I encountered an issue with the error message: "The `data-projection-id` prop does not match. Server: "null" Client: "4" at list item"

Recently utilized Framer Motion in one of my Next JS projects. Encountering an unconventional console error when attempting to refresh the page. The page is integrated with SSR from the latest version of Next JS (V13.X.X). The error message reads as follo ...

Utilizing the Laravel back-end API within the getServerSideProps() function in Next.js

Currently, my setup involves using next js for the front-end and laravel for the back-end. I am attempting to make an API call to the back-end (laravel) from the getServerSideProps() method as demonstrated below: export async function getServerSideProps(co ...

Issue encountered: Upon installation of sqlite3 in a nextron application, an error was encountered with the file ../node_modules/@mapbox/node-pre-gyp/lib/util/nw-pre

../node_modules/@mapbox/node-pre-gyp/lib/util/nw-pre-gyp/index.html Module parsing error: Unexpected token (1:0) An appropriate loader may be needed to handle this file type, as currently there are no configured loaders to process it. Refer to https://webp ...

What are the methods to manage rate limiting in Next.js 14?

I have recently started working with Next Js 14 and Mongo DB. While using Node Js, I learned about the Express Rate Limit package which allows for controlling the number of requests made by website users. If a user exceeds 200 requests in a span of 15 min ...

Router DOM in conjunction with Next.js

I am attempting to extract the output of the code in navigation, but unfortunately it is generating a dreadful error: Unhandled Runtime Error Error: You cannot render a <Router> inside another <Router>. You should never have more than one in ...

Exporting statically generated HTML using data fetched in Next.js

I am developing a React application that will display product ratings retrieved from the back-end. The rating of each product can be found at /product/{id}. Upon loading the page, the product's rating data will be fetched from the back-end and display ...

Deactivate automatic logins following a password reset with the clerk tool

Looking for help with implementing a "forgot password" feature in my Next.js project using Clerk. I've been following the official documentation provided by Clerk, but ran into an issue where users are automatically logged in after resetting their pas ...

Leveraging regular expressions for image domains within NextJS next.config.js

Is it possible to use regex in next.config.js to allow image domains? Giphy uses different numbers for its endpoints (e.g. media0.giphy.com, media2.giphy.com), but my regex isn't working and I'm seeing this error message: hostname "media0.gi ...

Is there a way to make all the burger bars change color when hovered over in my ReactJS/NextJS application?

Recently, I encountered an issue with my hamburger menu. When I hover over one of the bars, only that specific one changes color and not all of them. I am struggling to figure out how to make all the bars change color when any one of them is hovered over. ...

Tips for including an ID as the final segment of a URL in next.js

I am attempting to have the ID as the last part of the URL, but I am unsure about the syntax. Can someone assist me with this code in Next.js? <Link href="query/{itm._id}"> {Items.map((itm) => ( <Link href="query/{itm. ...

Issue encountered when constructing NextJS with @sentry/nextjs on AWS Amplify

I've been working on integrating Sentry with Next.js v12 using @sentry/nextjs and the Sentry wizard. Everything was running smoothly on localhost until I tried to build the app on AWS Amplify. During the SSR build, I encountered multiple errors relate ...

Retrieve HTML form data or an object within the getServerSideProps() function in NEXTJS

How can I submit form data from a NextJS page to another page with server-side rendering? The function getServerSideProps() on the receiving page requires these form data to make an API call. I considered using localStorage/sessionStorage to store the da ...

Are there any alternatives for altering the route and transmitting properties to a different component in Next.js?

Currently, I am located at this specific URL path: http://localhost:3034/dashboard/one. My next step involves passing a substantial object to another component called <Edit/>, which also includes modifying the URL path to become http://localhost:303 ...