Was trying to get familiar with nextJS 13.
What I encountered is getServerSideProps
function is not prerendering the page props. That’s my first time trying it, so I don’t know if I’m doing it wrong.
Here’s the code written in /app/login/page.js
import Content from "@/components/content";
import LoginForm from "@/components/loginForm";
import Title from "@/components/title";
function Login({ message }) {
return (
<Content>
<div className="ml-2 my-2">
{message || "NextJS is ok."}
<Title text="Login" />
</div>
<LoginForm />
</Content>
);
}
export default Login;
export async function getServerSideProps() {
console.log("running getServerSideProps function..");
return {
props: { message: "NextJS is awesome!" },
};
}
Key thing I’m trying to achieve here is to check the session key with axios request to the server before displaying login page. If user’s logged in, user should be redirected to homepage. Here’s future code if I will be able to make this function work:
export async function getServerSideProps() {
console.log("Im running getServerSideProps funct ");
let isLoggedIn = false;
try {
const response = await api.get("/users/session-check", {
withCredentials: true,
});
if (response.status === 200) isLoggedIn = true;
} catch (err) {
console.log(err.message);
}
if (isLoggedIn) {
return {
redirect: {
destination: "/",
permanent: false,
},
};
}
return {
props: {},
};
}
I tried to restart with npm run dev
Still getting the same results…
2
Answers
It looks like you’re trying to use
getServerSideProps
to perform server-side rendering and authentication checks before the page is displayed. From your code, it seems like you’re on the right track.However, I noticed that you’re not passing the props returned from
getServerSideProps
to yourLogin
component. In order for the server-side props to be passed to the component, you need to modify theLogin
function to accept themessage
prop like so:Additionally, since you’re using
getServerSideProps
, yournpm run dev
command won’t generate static HTML files for your pages. Instead, the pages will be generated on every request. So if you want to test ifgetServerSideProps
is working correctly, you’ll need to make a request to the page in your browser and check the console log for the output of yourconsole.log()
statement.I hope this helps! Let me know if you have any further questions.
So as I mentioned in a comment you should follow this https://nextjs.org/docs/app/building-your-application/data-fetching/fetching#async-and-await-in-server-components as you’re using Next 13 and the
app
folder.This means you can try something like this:
Of course you need to add your message props.