next-boost / next-boost

Add a cache layer for server-side-rendered pages with stale-while-revalidate. Can be considered as an implementation of next.js's Incremental Static Regeneration which works with getServerSideProps.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

User-Agent based caching

yasserzubair opened this issue · comments

Hello there. First of all, Thank you for making our lives easier. Having a great experience with next-boost.

I have a question about using next-boost with a specific use case.
I am serving different content based on different user agents.

This is how I am achieving this

import dynamic from 'next/dynamic'
import { withUserAgent } from 'next-useragent'

const DesktopContent = dynamic(() => import('./web'))
const MobileContent = dynamic(() => import('./mobile'))
 
 
 const Home = (props) => {

  const { ua, useragent } = props
  console.log(ua, useragent);
  return (
     <div>
        { ua && ua.isMobile ? (
        <MobileContent />
        ) : (
        <DesktopContent />
        ) }
     </div>
   )
 }

export default withUserAgent(Home);

When I access first time from PC, I see DesktopContent. But when I access it from mobile, I see a flash of DesktopContent and then MobileContent is displayed.

My question is, can I leverage it to cache based on user-agents. So that I may serve cache for a specific user agent.

Any help will be highly appreciated

Hi @yasserzubair,

Thanks for using next-boost!

When I access first time from PC, I see DesktopContent. But when I access it from mobile, I see a flash of DesktopContent and then MobileContent is displayed.

I see. After React is rehydrated, it shows your MobileContent.

Currently all cached pages are using the request's url as the key. And it won't work in your case, which different contents are returned for the same url.

The easiest way to solve this might be putting the contents on the same page and showing them based on CSS media query, although It might increase the page size.

@media screen and (max-width: 480px) {
  .mobile { display: ''; }
  .desktop { display: 'none'; }
}
@media screen and (min-width: 481px) {
  .mobile { display: 'none'; }
  .desktop { display: ''; }
}
<div>
  <div className="mobile"><MobileContent /></div>
  <div className="desktop"><DesktopContent /></div>
</div>

Thankyou for your support.

@yasserzubair The latest version has supported a function for customizing keys for cache. You can create 2 keys for the same URL, one for mobile and one for desktop. I think that would solve your problem.