Last active
March 30, 2023 12:12
-
-
Save NuroDev/a97966114e8771f903714c2e39a9ec46 to your computer and use it in GitHub Desktop.
π¦ Define app route handler β A basic function to define a new route handler for Next.js 13's app directory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type ByteFormatStr = "b" | "gb" | "kb" | "mb" | "pb" | "tb"; | |
type ByteSize = `${number}${ByteFormatStr}`; | |
interface NextApiConfig { | |
api?: { | |
bodyParser?: | |
| false | |
| { | |
sizeLimit: ByteSize; | |
}; | |
externalResolver?: boolean; | |
responseLimit?: ByteSize; | |
}; | |
runtime?: "edge" | "nodejs"; | |
regions?: Array<string>; | |
} | |
type NextRouteHandler< | |
TParams extends Record<string, unknown> = Record<string, unknown>, | |
TResponse extends Response = Response | |
> = (request: Request, params: { params?: TParams }) => TResponse | Promise<TResponse>; | |
type SupportedHTTPMethods = | |
| "DELETE" | |
| "GET" | |
| "HEAD" | |
| "OPTIONS" | |
| "PATCH" | |
| "POST" | |
| "PUT"; | |
type DefineAppRouteHandlerOptions<TParams extends Record<string, unknown>> = | |
Record<SupportedHTTPMethods, NextRouteHandler<TParams>> & NextApiConfig; | |
export function defineAppRouteHandler< | |
TParams extends Record<string, unknown> = Record<string, unknown>, | |
TOptions extends Partial<DefineAppRouteHandlerOptions<TParams>> = Partial< | |
DefineAppRouteHandlerOptions<TParams> | |
> | |
>(options: TOptions): TOptions { | |
return options; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// app/blog/[slug]/route.ts | |
import { NextResponse } from "next/server"; | |
import { defineAppRouteHandler } from 'path/to/util'; | |
export const { config, GET } = defineAppRouteHandler<{ slug: string }>({ | |
runtime: 'edge', | |
GET: (_req, { params }) => NextResponse.json({ | |
slug: params?.slug, | |
}), | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment