Andrii Radkevych
Andrii Radkevych

Reputation: 3442

Is there any way to make NextResponse.rewrite from the client

I've devided my pages folder on 2 sections:

And I do some rewrote on the server

import { NextRequest, NextResponse } from 'next/server';

const isMobile = (userAgent: string) =>
  /iPhone|iPad|iPod|Android/i.test(userAgent);

export function middleware(req: NextRequest) {
  const userAgent = req.headers.get('user-agent');
  const { pathname, origin } = req.nextUrl;

  if (userAgent && !pathname.includes('favicon.ico')) {
    if (isMobile(userAgent)) {
      return NextResponse.rewrite(`${origin}/mobile${pathname}`);
    } else {
      return NextResponse.rewrite(`${origin}/desktop${pathname}`);
    }
  }
}

It is great , I hadnle 2 sizes - more 1280 and lower , and on those 2 I have some breakpoints. But what is user for example switch from <1280 to >1280, is there any way to detect it on client ( there is ) and rewrite it same way as on _middleware ?

Upvotes: 0

Views: 603

Answers (1)

Ramakay
Ramakay

Reputation: 3145

One way to do this might be to use an observer that reports changes at an app level ( this kind of avoids the isDesktop like logic) - it unfortunately is doing isDesktop like logic but works more at a observer level.

i.e

// Modified from package example. 

import { Observe } from '@envato/react-breakpoints';

const exampleBreakpoints = {
    widths: {
      0: 'mobile',
      769: 'tablet',
      1280: 'desktop',

    }
  };

export const ExampleComponent = () => (
  <Observe breakpoints={exampleBreakpoints}>
    {({ observedElementProps, widthMatch = 'ssr' }) => (
      <div {...observedElementProps}>
        <div className={widthMatch}>
     <YourComponent />
      </div>
    )}
  </Observe>
);

https://github.com/envato/react-breakpoints

The interesting thing about this package is on the server, you will get undefined, see https://github.com/envato/react-breakpoints/blob/main/docs/server-side-rendering.md

Instead of doing user agent matching, you can reflect where the changes are happening, this means you can do SSR accordingly like you were doing.

I see the flow happening like below:

  1. User loads a page on Desktop - SSR gets undefined from so renders a Desktop page
  2. User resizes, ResizeObserverProvider will trigger and since its a provider, it will cascade the props to children who can use it.

This is one of the many ways to do it but it involves client side calculations.

Upvotes: 0

Related Questions