Issue
This Content is from Stack Overflow. Question asked by Zəhra Zamanoğlu
The website I am currently working on does not have a responsive design. Thus, the view I render depends on the client’s user agent. To do so, I need getServerSideProps
to decide which view I should render. On the other hand, considering the website’s needs, It’s better if I used getStaticProps
and revalidated it every 3 minutes. But, as you might know getStaticProps
and getServerSideProps
can not coexist. Is there any other way to get user agent headers?
Here is my code:
util.js
import * as Parser from "ua-parser-js";
export const isMobile = (req) => {
let ua;
if (req) {
ua = Parser(req.headers["user-agent"] || "");
} else {
ua = new Parser().getResult();
}
return (
ua?.device?.type === "mobile"
);
};
somepage.js
import { isMobile } from "util";
import { useEffect } from "react";
const SomePage = ({ isMobile }) => {
return isMobile ? <View1 /> : <View2 />;
};
export default SomePage;
export async function getServerSideProps({ req }) {
return {
props: {
isMobile: isMobile(req),
},
};
}
Solution
In your case , it’s better to use ISR
method , and it is implemented using getStaticProps
with interval . when there is cached version of the page , its returned to user with SSG
method , if cache does not exists or it’s not valid , the paged is rendered with SSR
method .
export async function getStaticProps() {
return {
props: {
},
revalidate: 10,
}
}
This Question was asked in StackOverflow by Zəhra Zamanoğlu and Answered by Moein Moeinnia It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.