Blog>
Snippets

Using the Next.js API Routes

Create an API route in Next.js and demonstrate data fetching from this API using fetch method in a Next.js page.
// pages/api/data.js
export default function handler(req, res) {
  res.status(200).json({ message: "Hello from the API" });
}
This is a serverless API route in Next.js. When a GET request is made to /api/data, it responds with a JSON object containing a greeting message.
// pages/index.js
import { useEffect, useState } from 'react';

export default function Home() {
  const [data, setData] = useState(null);

  useEffect(() => {
    async function fetchData() {
      const response = await fetch('/api/data');
      const data = await response.json();
      setData(data);
    }
    fetchData();
  }, []);

  return (
    <div>
      <p>{data ? data.message : 'Loading...'}</p>
    </div>
  );
}
This code is from a Next.js page that fetches data from the API route defined earlier. It uses a React hook to fetch the data when the component is mounted and renders the message received from the API.
/* styles/globals.css */
body {
  font-family: Arial, sans-serif;
}
This is a basic CSS file that applies a global font style to the body of the document.