1. Create an API endpoint:
First, create an API endpoint using Next.js API routes. You can create a new file under the pages/api directory. For example, let’s create a file named example.js:
// pages/api/example.js
// Example API route to fetch data
export default function handler(req, res) {
Simulated data for demonstration
const data = {
message: "Hello from the server!"
};
// Return the data as JSON
res.status(200).json(data);
}
2. Fetch Data on Your Page:
Next, fetch the data in your Next.js page component using getServerSideProps. This function runs on the server side and fetches data before rendering the page.
// pages/index.js
import React from 'react';
export default function Home({ message }) {
return (
<div>
<h1>{message}</h1>
</div>
);
}
export async function getServerSideProps() {
// Fetch data from the API endpoint
const res = await fetch('http://localhost:3000/api/example');
const data = await res.json();
// Pass data as props to the page component
return {
props: {
message: data.message
}
};
}
3. Run Your Next.js App:
Run your Next.js app and navigate to the page where you’ve implemented the API data rendering. You should see the data fetched from the API endpoint displayed on the page.