1

I'm building the pages for my Next.js app and have a page that is only part of the mobile design. I'm wondering how do I only serve this page to people who navigate to it on mobile -- then on desktop if they request this page default to homepage or an error?

/pages
   index.js
   mobile-only.js

Andy Tran
  • 135
  • 2
  • 9

1 Answers1

0

You can try to parse useragent header in getServerSideProps and redirect accordingly.

There you can find RegExes that you can use: Detecting a mobile browser

Example of getServerSideProps function:



export const getServerSideProps = async ({ req }) => {
  // You need to make this function `parseUA` by yourself 
  const isMobile = parseUA(req.headers['user-agent'])

  if (!isMobile) {
    return {
      redirect: {
        destination: '/some/other/page',
        permanent: false
      }
    }
  }

  // Your regular logic for mobile page here 

  return {
    props: {
      data: {
        // ...
      }
    },
  };
};
Danila
  • 15,606
  • 2
  • 35
  • 67
  • Asking this follow-up question because I don't want to implement server-side client detection logic as a first solution, do you follow any principles when it comes to creating pages? Visually the routing on my app follows different paths from mobile to desktop (e.g integral components showing in different navigation interactions). I'm thinking if it would be a solution to not create a separate mobile-only page, but rather use state to manage how these components show. @Danila – Andy Tran Mar 06 '21 at 05:13
  • 1
    NextJs way it to handle stuff like that on server-side, otherwise there is no reason to use it over let's say CRA if you don't need SSR. If someone visit your mobile page on desktop and you only have client side logic to detect how components look then user will see desktop version first before javascript will be able to hydrate it client side. – Danila Mar 06 '21 at 09:13