Trying to get familiar with nextJS 13.
What I encountered was that the getServerSideProps
function did not prerender page props. This is my first time trying it so I don't know if I'm doing it wrong.
Here is /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!" }, }; }
The key thing I'm trying to achieve here is to check the server's session key using an axios request before displaying the login page. If the user is logged in, the user should be redirected to the homepage. If I can get this to work, here's the code for the future:
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 using npm run dev
Still getting the same result...
It looks like you are trying to use
getServerSideProps
to perform server-side rendering and authentication checks before displaying the page. Judging from your code, you seem to be on the right track.However, I noticed that you are not passing the props returned from
getServerSideProps
to yourLogin
component. In order to pass server-side properties to the component, you need to modify theLogin
function to accept themessage
property as follows:Additionally, since you are using
getServerSideProps
, yournpm run dev
command will not generate static HTML files for your page. Instead, pages will be generated on every request. So if you want to test thatgetServerSideProps
is working properly, you need to make a request to the page in the browser and check the console log for theconsole.log( )
statement.I hope this helps! If you have any other questions, please let me know.
So, as I mentioned in the comments, you should follow this https://nextjs.org/docs/app/building-your-application/data-fetching/fetching#async-and-await -in-server-components when you use Next 13 and
app
folders.This means you can try something like this:
Of course, you need to add message props.