So, my instructor building an application, he told me to use getServerSideProps(context
).
Since Next.js updated, I want to know what context means and what does it holds? Since the course was outdated, can any please tell me the alternative method? here’s my instructor code:
userPage.jsx:
import { getSession } from "next-auth/react";
import React from "react";
const UserPage = () => {
return <div>User</div>;
};
export default UserPage;
export async function getServerSideProps(context) {
const session = await getSession(context);
console.log("sess", session);
return {
props: {},
};
}
I tried and searched a lot for this and iam tired for this. Please Ignore This Question if you think this is Stupid 🙂
2
Answers
Context provides information about the request, including matched params for dynamic routes, query parameters, request cookies, and more.
You can find more information about the context parameter in the official documentation.
If you’d like to upgrade to use the
/app
directory pattern, you can follow this migration guide. In short, you’ll use React Server Components to directlyfetch
the data you need for your component.The
context
parameter is a special object that holds various pieces of information related to the current HTTP request being processed. Note thatcontext
object in each server-side functions (getStaticProps..) is different because their environment is different.getServerSideProps
runs with every requst.If you look at the docs, each key is related to the HTTP request.
req
andres
objects are similar inexpress
. Here you do not need to send anything withres.send
like inexpress.js
because Next.js will do it automatically (its response is the rendered component). But you can intervene in and manipulate theres
object by adding extra headers or cookies.with
req
you can intervene in incoming request and read the incoming data, headers,cookies etc. so you can check if the user authenticated or notparams
is useful to read the dynamic part of the page. In dynamic pages,param
usually refers toid
of stored data so you fetch the data on the server by using the id