Skip to content

Instantly share code, notes, and snippets.

@NuroDev
Last active March 30, 2023 12:12
Show Gist options
  • Save NuroDev/a97966114e8771f903714c2e39a9ec46 to your computer and use it in GitHub Desktop.
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
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;
}
// 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