Next.js 13 app dir Route handler with Typescript

Next.js 13 app dir Route handler with Typescript

2023-05-12
3 min read

Overview

Route handler is used to custom request handler using the Web Request and Response APIs. Route handler is equivalent of API routes in page directory. Route handlers must be defined in a route.js | ts inside app directory like app/api/route.ts. Although Route handler can be nestd inside the app directory like page, layout and loading files, route file should be in different route segment level as page.

HTTP Methods

Route handler supports following methods GET, POST, PUT, PATCH, DELETE, HEAD and OPTIONS. Next.js will return 405 Method Not Allowed error if you call an unsupported Methods.

Example

tsx
// app/api/hello/route.ts
export async function GET(request: Request) {
  return new Response('Hello, Next.js world!')
}
export async function POST(request: Request) {...}
export async function PUT(request: Request) {...}
export async function PATCH(request: Request) {...}
export async function DELETE(request: Request) {...}
export async function HEAD(request: Request) {...}
export async function OPTIONS(request: Request) {...}

API URL follows your folder path. In this case, APIs will be /api/hello.

Search params

tsx
import { NextResponse, NextRequest } from 'next/server'

interface SearchParam {
  [p: string]: string
  search: string
}

export async function GET(request: NextRequest) {
  const searchPrams = Object.fromEntries(request.nextUrl.searchParams) as SearchParam

  return NextResponse.json({
    ...searchPrams
  })
}

The searchParams in nextUrl property helps you to get URLSearchParams type using the standard Web API methods. Before using nextUrl in request, you have to set request parameter type to NextRequest. In PRO tip, Object.fromEntries will return search param values to JSON.

Params

tsx
// api/[id]/routes.ts
import { NextResponse } from 'next/server'

interface Context {
  params: {
    id: string
  }
}

export async function GET(request: Request, context: Context) {
  return NextResponse.json(params)
}

Params is Object type in a second parameter. NextResponse.json() allows to return data as Object type, so it will return {"params":{"id":"test"}}.

Receive data

Route handler provides both JSON in body and FormData.

Body

tsx
export async function POST(request: Request) {
  const payload = await request.json()

  return NextResponse.json({
    ...payload,
  })
}

The json() promise function in request helps you to get data in body using the standard Web API methods.

Form data

tsx
export async function POST(request: Request) {
  const payload = Object.fromEntries(await request.formData())

  return NextResponse.json({
    ...payload,
  })
}

The formData() promise function in request helps you to get form data as FormData type using the standard Web API methods. Click here to see more methods. In PRO tip, Object.fromEntries will return formData values to JSON.

Get Cookies

According to document, there are two ways to get Cookies

Way 1.

tsx
import { cookies } from 'next/headers';
 
export async function GET(request: Request) {
  const cookieStore = cookies();
  const token = cookieStore.get('token');
 
  return new Response('Hello, Next.js!', {
    status: 200,
    headers: { 'Set-Cookie': `token=${token}` },
  });
}

The cookies function from next/headers allows to get read-only cookie instance. If you would like to set-cookie, you have to return a new Response adding a Set-Cookie key in header.

Way 2

tsx
import { type NextRequest } from 'next/server';
 
export async function GET(request: NextRequest) {
  const token = request.cookies.get('token');
}

you can use abstractions on top of the underlying Web APIs to read cookies. NextRequest extends the Web Request API with additional convenience methods. The token variable will have { name: 'token', value: 'tokenValue' }. You also can add, update or delete cookies.

typescript
request.cookies.set('token', 'new token');
request.cookies.delete('token');
request.cookies.clear();

Get Headers.

According to document, it also has two ways to get Header.

Way 1

tsx
import { headers } from 'next/headers';
 
export async function GET(request: Request) {
  const headersList = headers();
  const barer = headersList.get('barer');
 
  return new Response('Hello, Next.js!', {
    status: 200,
    headers: { barer: barer },
  });
}

Way 2

tsx
import { type NextRequest } from 'next/server';
 
export async function GET(request: NextRequest) {
  const requestHeaders = new Headers(request.headers);
}

Both ways are very similar as ways for Cookies

Redirect

tsx
import { redirect } from 'next/navigation';
 
export async function GET(request: Request) {
  redirect('https://requiem-blog.netlify.app/');
}

The redirect functions allows you to redirect page to URL.

Ref

Free open source project made by Youngjin