-1

I'm trying to make my page SEO friendly by using getServerSideProps method. I have tried to google it but cannot find any specifc example for my case. I'm not sure how to do it. I have a useEffect method currently.

import Header from './Header.js';
import Footer from './Footer.js';
import React, { Component, useState, useEffect }  from 'react';
import Link from 'next/link';
import { useParallax, ParallaxBanner } from "react-scroll-parallax";
import { useTranslation } from "react-i18next";
import axios from "axios";
//import { Link, useLocation } from 'react-router-dom';

import Post from "./Post";

function Article({postSlug}) {

     const { t, i18n } = useTranslation();
     const [post, setPost] = useState([]);
     const [posts, setPosts] = useState([]);
     const currentlocale = typeof window !== 'undefined' ? localStorage.getItem('locale') : null;
     
     useEffect(() => {

        if(postSlug){
            axios({
            method: "POST",
            url: process.env.NEXT_PUBLIC_API_URL + '/pages/article',
            headers: { 'Content-Type': 'application/json;charset=UTF-8', "Access-Control-Allow-Origin": "*", "Accept": "application/json" },
            data: {
                country: currentlocale,
                slug: postSlug
            }
            }).then(result => {
                setPost(result.data.json.article);
                setPosts(result.data.json.articles);
                
            });
        }
          
     }, [postSlug])

    return (
        <div id="web-front">

            <Header />

            {post.title}

            <Footer />

        </div>
    )
}

export default Article;
Brian Millot
  • 179
  • 1
  • 12
  • The react effects are clientside. getServerSideProps is a special method that runs serverside right before the react component is mounted and will run only if the component is defined under `/pages` folder structure. – assembler Jan 11 '23 at 03:46

1 Answers1

0
  • getServerSideProps only runs on routes / files created inside /pages folder.

  • Move your data fetching methods from the component to the getServerSideProps function.

  • You can get postSlug from the context.req[1] object getServerSideProps receives.

  • LocalStorage won't be available on server. Instead use cookies as a replacement for localStorage, since cookies is available on the context.req object. [2]

function Article({ initialPost, initialPosts }) { // received from ssr props
  const { t, i18n } = useTranslation();
  const [post, setPost] = useState(initialPost); // set initially
  const [posts, setPosts] = useState(initialPosts); // set initially

  return (
    <div id="web-front">
      <Header />

      {post.title}

      <Footer />
    </div>
  );
}

export async function getServerSideProps(ctx) {
  const postSlug = ctx.req.params.postSlug; //  handled by you

  const currentLocale = getCurrentLocaleFromCookies(ctx.req); //  handled by you

  let initialData = {};

  try {
    initialData = await axios({
      method: 'POST',
      url: process.env.NEXT_PUBLIC_API_URL + '/pages/article',
      headers: {
        'Content-Type': 'application/json;charset=UTF-8',
        'Access-Control-Allow-Origin': '*',
        Accept: 'application/json',
      },
      data: {
        country: currentlocale,
        slug: postSlug,
      },
    });
  } catch (err) {
    console.error(err);
  }

  return {
    props: {
      initialPost: initialData.data.json.article,
      initialPosts: initialData.data.json.articles,
    },
  };
}

export default Article;

Reference:

  1. https://nextjs.org/docs/api-reference/data-fetching/get-server-side-props
  2. https://stackoverflow.com/a/63875689/7679903
Badal Saibo
  • 2,499
  • 11
  • 23