How to usereq object in getServerSideProps in Next.js
In server-side rendering methods like getServerSideProps, you have access to the req object. If req is defined, it signifies that the code is executing on the server side. Since getServerSideProps exclusively operates on the server, any code within it will not be executed on the client side. Therefore, the else part meant for client-side execution will not be triggered.
Example:
//index.js
import Head from "next/head";
export default function Home({ isServer }) {
if (isServer) {
console.log("Application is on server side");
}
return (
<>
<Head>
<title>Create Next App</title>
</Head>
<main>
<h2>This is a demo page</h2>
</main>
</>
);
}
export async function getServerSideProps(context) {
return {
props: {
isServer: !!context.req,
},
};
}
Output:
Detecting server vs client in NextJS application
Next.js, a popular React framework, helps you to build powerful web applications with ease. However, managing server-side and client-side execution can pose unique challenges. In this article, we’ll explore techniques for detecting server or client execution in Next.js applications.
Table of Content
- What is Server Side Rendering?
- What is Client Side Rendering?
- Detecting server vs client-side rendering
- 1: Using typeof window
- 2: Using process.browser
- 3: Using a custom flag
- 4: Using req object in getServerSideProps
- 5: Using window object inside useEffect