0
0
NextJSframework~5 mins

Async server components in NextJS

Choose your learning style9 modes available
Introduction

Async server components let you fetch data or do tasks before showing the page. This makes your app faster and smoother.

When you want to load data from a database or API before showing the page.
When you need to do some calculations or prepare info on the server first.
When you want to keep your page fast by loading only what is needed.
When you want to avoid loading spinners by fetching data before rendering.
When you want to use server-only code safely without sending it to the browser.
Syntax
NextJS
export default async function ComponentName() {
  const data = await fetchData();
  return (
    <div>{data}</div>
  );
}
The component function is marked with async so you can use await inside.
You can fetch data or do other async tasks before returning the JSX to render.
Examples
This example fetches a greeting message from an API and shows it inside an <h1> tag.
NextJS
export default async function Greeting() {
  const res = await fetch('https://api.example.com/hello');
  const message = await res.text();
  return <h1>{message}</h1>;
}
This example shows the current time. It uses async but no await here, which is allowed.
NextJS
export default async function Time() {
  const now = new Date().toLocaleTimeString();
  return <p>Current time: {now}</p>;
}
Sample Program

This component fetches a random joke from an API before rendering. It shows the setup and punchline inside a section with an accessible label.

NextJS
async function getRandomJoke() {
  const res = await fetch('https://official-joke-api.appspot.com/random_joke');
  if (!res.ok) throw new Error('Failed to fetch joke');
  return res.json();
}

export default async function Joke() {
  const joke = await getRandomJoke();
  return (
    <section aria-label="Random joke">
      <h2>Here's a joke for you:</h2>
      <p><strong>{joke.setup}</strong></p>
      <p>{joke.punchline}</p>
    </section>
  );
}
OutputSuccess
Important Notes

Async server components run only on the server, so you can safely use secrets or server-only code.

They help reduce loading spinners by fetching data before sending HTML to the browser.

Remember to handle errors in async calls to avoid breaking the page.

Summary

Async server components let you fetch data before showing the page.

Use async and await inside the component function.

This improves speed and user experience by sending ready HTML to the browser.