How to use wp-json on Next.js? post image

How to use wp-json on Next.js?

(Updated May 05, 2024)

How to use wp-json on Next.js? (Because who wants to code more than they have to?)

Hey everyone, it’s your favorite tech blogger here, back with another post! Today, I’m going to delve into the world of headless WordPress and Next.js, specifically focusing on that nifty little feature: wp-json.

Now, I’ll be honest, I like to write code about as much as I enjoy doing my taxes. But sometimes, you gotta do what you gotta do. That’s where wp-json comes in – a lifesaver for lazy developers like myself (and maybe you too?).

In this post, you’ll learn how to leverage wp-json with Next.js to create a dynamic and content-driven website, all without writing a novel’s worth of code. Plus, as a little bonus, I’ll reveal how this very blog you’re reading is using wp-json with Next.js under the hood!

What is wp-json and Why Should You Care?

Imagine your WordPress site as a treasure trove of content, locked away in a vault. wp-json acts like a magical key, unlocking that content and making it accessible to your Next.js application. It’s essentially a REST API built into WordPress, allowing you to fetch posts, pages, comments, and more – all in a structured format.

Why is this cool? Because it lets you decouple your frontend (Next.js) from your backend (WordPress). This means you can build a blazing-fast, modern frontend experience using Next.js, while still leveraging the robust content management features of WordPress.

Here are some of the benefits of using wp-json with Next.js:

  • Improved Performance: Next.js excels at static site generation and server-side rendering, leading to a faster and more responsive user experience.
  • Flexibility: Build your frontend entirely independent of the WordPress theme, giving you complete control over the design and user experience.
  • SEO Friendly: Next.js takes care of SEO best practices out of the box, ensuring your content remains discoverable in search engines.
  • Content Management Made Easy: Continue to edit and manage your content seamlessly within the WordPress admin interface.

Alright, that’s enough theory, let’s get coding!

Fetching Posts with getServerSideProps

Next.js provides a powerful function called getServerSideProps that allows you to fetch data from external sources, like our good friend wp-json, before the page renders on the server. This ensures your components always have access to the latest content.

Here’s a code snippet demonstrating how to use getServerSideProps to fetch posts from a WordPress site:

JavaScript

export async function getServerSideProps(context) {
  const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/posts`);
  const posts = await res.json();

  return {
    props: {
      posts,
    },
  };
}

function MyBlogPost({ posts }) {
  // Render your blog posts here using the 'posts' data
  return (
    <div>
      <h1>My Awesome Tech Blog Posts</h1>
      {posts.map((post) => (
        <article key={post.id}>
          <h2>{post.title.rendered}</h2>
          <div dangerouslySetInnerHTML={{ __html: post.content.rendered }} />
        </article>
      ))}
    </div>
  );
}

export default MyBlogPost;

Explanation:

  1. We define an async function called getServerSideProps.
  2. Inside this function, we use the fetch API to retrieve data from the WordPress REST API endpoint (/posts). The URL is constructed using an environment variable (NEXT_PUBLIC_API_URL) to store the base URL of your WordPress site.
  3. We parse the response as JSON and store the posts data in a variable called posts.
  4. Finally, we return an object with the posts data as props, which will be available to our component (MyBlogPost).

Psst! Don’t forget to set the NEXT_PUBLIC_API_URL environment variable in your Next.js project to point to your WordPress site’s wp-json endpoint.

Bonus: How This Blog Uses wp-json with Next.js

Surprise! As promised, here’s a little secret: this very blog you’re reading is built with Next.js and leverages wp-json to fetch all the content you see on the screen. Each blog post is a separate Next.js page that uses getServerSideProps to grab the post data dynamically. This allows for a smooth and performant reading experience while keeping the content management process familiar and user.

Subscribe

Get an email when i write new posts. Learn animation techniques, CSS, design systems and more