Complete the code to fetch data on the server side in Next.js using the recommended method.
export async function [1]() { const res = await fetch('https://api.example.com/data'); const data = await res.json(); return { props: { data } }; }
In Next.js, getServerSideProps is used to fetch data on the server side at request time.
Complete the code to fetch static data at build time in Next.js.
export async function [1]() { const res = await fetch('https://api.example.com/data'); const data = await res.json(); return { props: { data } }; }
getStaticProps fetches data at build time, generating static pages.
Fix the error in this Next.js page component by choosing the correct data fetching method.
function Page({ data }) {
return <div>{data.message}</div>;
}
export async function [1]() {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
return { props: { data } };
}
export default Page;The page uses static props, so getStaticProps is the correct method to fetch data at build time.
Fill both blanks to create a Next.js API route that returns JSON data.
export default function handler(req, res) {
if (req.method === '[1]') {
res.status(200).json({ message: '[2]' });
} else {
res.status(405).end();
}
}API routes handle HTTP methods like GET. The message can be any string, here 'Hello from API'.
Fill all three blanks to fetch data in a React Server Component in Next.js 13+.
import React from 'react'; async function fetchData() { const res = await fetch('[1]'); return res.[2](); } export default async function Page() { const data = await fetchData(); return <main><h1>[3]</h1></main>; }
text() instead of json() for JSON data.The fetch URL is the API endpoint, json() parses the response, and the heading displays a welcome message.