API call

Create API routes in Next.js App Router. This tutorial shows you how to create and use API endpoints.

Create an API route

Create an API route by creating a route.ts file in the app/api directory:

app/api/hello/route.ts
1import { NextRequest, NextResponse } from 'next/server';
2
3export async function GET(request: NextRequest) {
4  return NextResponse.json({ message: 'Hello from API!' });
5}
6
7export async function POST(request: NextRequest) {
8  const body = await request.json();
9  return NextResponse.json({ received: body });
10}

Call API from client

Call your API from a client component:

app/components/ApiCallExample.tsx
1'use client';
2
3import { useState } from 'react';
4
5export default function ApiCallExample() {
6  const [data, setData] = useState(null);
7  const [loading, setLoading] = useState(false);
8
9  const fetchData = async () => {
10    setLoading(true);
11    const response = await fetch('/api/hello');
12    const json = await response.json();
13    setData(json);
14    setLoading(false);
15  };
16
17  return (
18    <div>
19      <button onClick={fetchData} disabled={loading}>
20        {loading ? 'Loading...' : 'Fetch Data'}
21      </button>
22      {data && <pre>{JSON.stringify(data, null, 2)}</pre>}
23    </div>
24  );
25}

Call API from server

Call your API from a server component:

app/server-component/page.tsx
1async function getData() {
2  const res = await fetch('http://localhost:3000/api/hello', {
3    cache: 'no-store', // Don't cache for dynamic data
4  });
5  
6  if (!res.ok) {
7    throw new Error('Failed to fetch data');
8  }
9  
10  return res.json();
11}
12
13export default async function ServerComponent() {
14  const data = await getData();
15  
16  return (
17    <div>
18      <h1>{data.message}</h1>
19    </div>
20  );
21}

Handle errors

app/api/data/route.ts
1import { NextRequest, NextResponse } from 'next/server';
2
3export async function GET(request: NextRequest) {
4  try {
5    // Your API logic here
6    const data = await fetchData();
7    return NextResponse.json(data);
8  } catch (error) {
9    return NextResponse.json(
10      { error: 'Internal Server Error' },
11      { status: 500 }
12    );
13  }
14}