This project demonstrates different methods of communicating with APIs in a Next.js application, showcasing Server-Side Rendering (SSR), Client-Side Rendering (CSR), Incremental Static Regeneration (ISR), and Static Site Generation (SSG).
- SSR is a method where the content is fetched and rendered on the server for each request.
- This is suitable when you need to fetch data that should always be up-to-date and delivered on the initial request.
const ServerSideRendering = async()=>{
const response = await axios.get(`${process.env.NEXT_PUBLIC_API_URL}`,{
cache: 'no-store'
})
return response.data
}
const SSRapp = async() => {
const data = await ServerSideRendering()
return(
<div>
<h1>Server Side Rendering</h1>
<p>{JSON.stringify(data)}</p>
</div>
)
}- CSR is a method where the content is fetched on the client side after the initial page load.
- This is used when data doesn't need to be pre-rendered and can be fetched after the page is loaded in the browser.
"use client" // use "use client" instead of "use server"
import { useState,useEffect } from 'react'
import axios from 'axios'
const ClientSideRendering = ()=>{
const [data,setData] = useState([]);
const getData = async()=>{
try {
const response = axios.get(`${process.env.NEXT_PUBLIC_API_URL}`)
setData(response.data)
} catch (error) {
console.
error('Error fetching data', error)
}
}
useEffect(()=>{
getData()
},[]) // run getData only once when component mounts
return (
<div>
<h1>Client Side Rendering</h1>
<p>{JSON.stringify(data)}</p>
</div>
)
}
export default ClientSideRendering;- SSG pre-renders content at build time, which makes it very fast as the content is served as static HTML.
- It’s used when data is static and doesn’t change often.
const ServerSiteGeneration = async()=>{
const response = await axios.get(`${process.env.NEXT_PUBLIC_API_URL}`,{
cache: 'force-cache'
})
return response.data
}
const SSGapp = async() => {
const data = await ServerSiteGeneration()
return(
<div>
<h1>Static Side Generation</h1>
<p>{JSON.stringify(data)}</p>
</div>
)
} - ISR allows you to update static content without rebuilding the entire site.
- It’s useful when you want static content but also need to refresh the content at regular intervals.
const IcrementalStaticRegeneration = async()=>{
const response = await axios.get(`${process.env.NEXT_PUBLIC_API_URL}`,{
next:{revalidate:60} // revalidate every 60 seconds
})
return response.data
}
const SSRapp = async() => {
const data = await IcrementalStaticRegeneration()
return(
<div>
<h1>Incremental Static Regeneration</h1>
<p>{JSON.stringify(data)}</p>
</div>
)
}To set up the Nextjs Api Communication test project locally, follow these steps:
-
Clone the repository:
git clone https://github.com/RIADH-NOURI/nextjs-api-communication.git cd nextjs-api-communication -
Install dependencies:
npm install
- Run the application:
npm run dev