How to create an API route in Next.js 15?

In Next.js 15, API routes are created using the App Router with a file named route.ts or route.js inside the app/api directory. Here's a minimal example:

bash
app/api/hello/route.ts
ts
export async function GET() { return new Response(JSON.stringify({ message: 'Hello world' }), { status: 200, headers: { 'Content-Type': 'application/json' } }) }

You can now access the API at /api/hello.

Would you like an example with POST or dynamic routes?

how to call this API from Zustand action?
ts
import { create } from 'zustand' const useStore = create((set, get) => ({ data: null, fetchData: async () => { const res = await fetch('/api/hello') if (!res.ok) return const json = await res.json() set({ data: json }) } }))
How use /api/notes/ endpoing that have one paramter the name of the note
ts
import { create } from 'zustand' const useStore = create((set, get) => ({ note: null, fetchNote: async (name) => { const res = await fetch(`/api/notes/${encodeURIComponent(name)}`) if (!res.ok) return const json = await res.json() set({ note: json }) } }))
What ablut the code for the route? How to access the param?
ts
// app/api/notes/[name]/route.ts import { NextRequest } from 'next/server' export async function GET( req: NextRequest, { params }: { params: { name: string } } ) { const { name } = params // example response return new Response( JSON.stringify({ note: `Content for ${name}` }), { status: 200, headers: { 'Content-Type': 'application/json' } } ) }
Do you have some kind of generic for the second argument that accept the params type: type Params = { name: string; }

Yes, you can define a generic type for the context parameter. Here's how to do it cleanly with a Params type:

ts
import { NextRequest } from 'next/server' type Params = { name: string } export async function GET( req: NextRequest, context: { params: Params } ) { const { name } = context.params return new Response( JSON.stringify({ note: `Content for ${name}` }), { status: 200, headers: { 'Content-Type': 'application/json' } } ) }

This keeps your types reusable and clear. Do you want to handle query parameters or just route params like this?

How to use query string to for the name in the route?

To use a query string (e.g. /api/notes?name=test) instead of a dynamic route, do this:

ts
// app/api/notes/route.ts import { NextRequest } from 'next/server' export async function GET(req: NextRequest) { const { searchParams } = new URL(req.url) const name = searchParams.get('name') if (!name) { return new Response( JSON.stringify({ error: 'Missing name param' }), { status: 400 } ) } return new Response( JSON.stringify({ note: `Content for ${name}` }), { status: 200, headers: { 'Content-Type': 'application/json' } } ) }

Then fetch it with:

ts
await fetch('/api/notes?name=test')

Do you prefer this over route parameters?

Create me code that will use SearchParam to create new query string for the fetch based on the name variable
ts
const getNoteUrl = (name) => { const params = new URLSearchParams({ name }) return `/api/notes?${params.toString()}` } // usage const url = getNoteUrl('example') const res = await fetch(url)

ChatGPT może popełniać błędy. Sprawdź ważne informacje. Zobacz Preferencje dotyczące plików cookie.