Home > Blockchain >  fetch data by useEffect in a server side rendering page
fetch data by useEffect in a server side rendering page

Time:02-06

I have a project with react js and next js. I am developing a dynamic page, with getStaticPaths and getStaticProps. So I am fetching most of the data in getStaticProps to make the page be rendered on server side.
But there are some data which I can't fetch on server side, because it needs token which is stored in local storage.

The question is, if I use useEffect hook to fetch those data on client side, does this all process make any advantage for SEO? Or I have to change structures, and store token in cookies to fetch all data on server side?

CodePudding user response:

If you need a token to fetch said data, that data is probably related to the user? Hence, doesn't and shouldnt be considered with SEO.

If your data is not specifically for the user. Consider making it accessable without token

CodePudding user response:

You can check no problem on the server side whether a user is logged in only when you use getServerSideProps - getStaticProps are executed at a built time so there is no communication with whatever user inputs into the UI simply because thats a different time frame: building the app on the server, only when the app is built user can interact with it. But getServerSideProps are not executed at a built time, yet there are still executed on the server side and since useEffect is a frontend API it won't work there. So there are two ways:

  1. If you use NextAuth - you can use getServerSideProps and on the context object you have 'req' property and the property passed to the getSession function (you need to import that function) will tell you whether user has a session or not. Here is an example code snipet:

    `import { getSession } from 'next-auth/react';

    // some code here like your frontend component

    export const getServerSideProps = async (context) => { const { req, res } = context;

    const session = await getSession({ req: req });

    if (!session) { return { redirect: { destination: '/', permanent: false }, };

    }

    const email = session. user.email;

    return { props: { email: email, session }, }; };`

Here is more on the subject from the official next docs: https://nextjs.org/docs/authentication

  1. If you don't use NextAuth I am sure you can attach your token to the context object like in the example above and read it in getServerSideProps except not use getSession as that is NextAuth API. haven't done it though.
  • Related