0

I want to implement Server Sider Rending SSR for a NextJS Typescript component. It's possible to do SSR for a page using getServerSideProps but not found any way for non page child components. It works fine under page folder but no luck outside of page components.

Say I have created a component with API under components folder, here getServerSideProps is not working and even SSR also not working. and can't see the content in page view source DOM.

/components/user.tsx

import React from 'react';
import {useEffect,useState} from 'react';

interface User {
    id:number;
    name: string;
    username: string;
    email:string;
  }
  
const Users = () => {
  const [data,setData]= useState([])
  useEffect(()=>{
    fetch("https://jsonplaceholder.typicode.com/users").then((result)=>{
      result.json().then((resp)=>{
        setData(resp);
      })
    })
  },[])
  console.log(data)
    return (
        <div>
            <ul>
                {data.map((data: User)=>
                <li key={data.id}>
                    <h2>{data.name}</h2>
                    <h3>{data.username}</h3>
                    <h4>{data.email}</h4>
                </li>
                )}
            </ul>
        </div>
    )
}
export default Users

/pages/user.tsx

import React from 'react';
import Users from "../components/Users";

function user() {
  return (
    <section>
      <h1>User - Component</h1>      
      <main>
        <Users />
      </main>   
       
    </section>
  );
};

export default user;

Can you please help how to implement SSR for components which located out side of pages folder?

Sujit Paul
  • 29
  • 4
  • Does this answer your question? [NEXTJS: getServerSideProps not working into components](https://stackoverflow.com/questions/64136025/nextjs-getserversideprops-not-working-into-components) – juliomalves Feb 16 '22 at 19:04

1 Answers1

0

As it notes in the documentation

getServerSideProps can only be exported from a page. You can’t export it from non-page files.

This rules out getServerSideProps, now for the ask itself

Two options

  1. setup a corresponding pages/component page
  2. Setup a custom server and use the following in next.config.js - This allows routing to be on you without using the pages as the only place things get served from.
module.exports = {
  useFileSystemPublicRoutes: false,
}
Ramakay
  • 2,919
  • 1
  • 5
  • 21