JAVASCRIPT

Pre-rendering Data from an API with Next.js getStaticProps

Implement server-side pre-rendering with Next.js `getStaticProps` to fetch external API data at build time, improving page performance and SEO.

// This file would be pages/index.js or pages/posts/[id].js in a Next.js project
import React from 'react';

// Example type for fetched data
type Post = {
  id: number;
  title: string;
  body: string;
};

// Component to display the fetched data
function BlogPost({ post }: { post: Post }) {
  if (!post) {
    return <p>Post not found.</p>;
  }
  return (
    <div>
      <h1>{post.title}</h1>
      <p>{post.body}</p>
    </div>
  );
}

// getStaticProps runs only on the server-side at build time
export async function getStaticProps() {
  const res = await fetch('https://jsonplaceholder.typicode.com/posts/1'); // Fetch specific post
  const post: Post = await res.json();

  // If the post is not found, return notFound: true
  if (!post || Object.keys(post).length === 0) {
    return {
      notFound: true,
    };
  }

  return {
    props: {
      post,
    },
    // Next.js will attempt to re-generate the page:
    // - When a request comes in
    // - At most once every 10 seconds
    revalidate: 10, // In seconds
  };
}

export default BlogPost;
How it works: This Next.js example demonstrates `getStaticProps`, a function used for static site generation (SSG) to fetch data from an external API at build time. It runs exclusively on the server, allowing pre-rendering of page content with data from a source like a REST API. The fetched `post` data is passed as props to the `BlogPost` React component. The `revalidate` option enables Incremental Static Regeneration (ISR), instructing Next.js to re-generate the page in the background after a certain interval if a new request comes in, keeping content fresh without a full rebuild.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs