Search code examples
javascriptreactjsnext.jsdynamic-routinggetstaticprops

fetch data by useEffect in a server side rendering page


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?

Update:
I want to check if user is logged in, and based on the result, show the page in different styles. But no user-related data is going to be rendered.
Right now, my code looks like this:

export default function BookDetail(props) {
  const [isLoggedIn, setIsLoggedIn] = React.useState(false);
  React.useEffect(() => {
    // It captures token from local storage
    const token = localStorage.getItem("token");
    // Then I need to confirm that token is valid from backend
    if (token) {
      setIsLoggedIn(true);
    }
  }, []);

  return (
    <div>
      { !isLoggedIn ? (
        {props.res.data.title}
        <br/>
        {props.res.data.description}
      ) : (
        {props.res.data.title}
        <br/>
        <button type="button" onclick={()=>{window.location.href='http://example.com';}} 
      )}
    </div>
  );
}

Solution

  • 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.

    Edit based on the comments here:

    Fetching data inside useEffect will absolutely affect SEO. You want to display part of a book (text) for users that are not logged in. You check if users are logged in by a request from the useEffect, this is fine and standard.

    If you want to Google to be able to read your book-text with crawlers you can not fetch it in useEffect, I suggest the following:

    in your getStaticProps: Fetch the data (book text) and pass it to your page. Display this information by default.

    Then in your useEffect you check if the user is logged in. If they are --> remove the text and render a button instead.

    This way, Google will read it as you intend, while logged in users will only see a button.