Use Next.js with PostgREST effortlessly.
npm install next-postgrest
// app/api/[[...rest]]/route.ts
import { NextPostgrest } from "next-postgrest";
export const { GET, POST, PUT, DELETE, PATCH } = NextPostgrest({
url: "http://postgrest:3333",
basePath: "/api",
before({ pathname, searchParams, view, request }) {
// Validate something
if (Object.keys(searchParams).includes("myField")) {
return new Response(JSON.stringify({ message: "bad request" }), {
status: 400,
});
}
},
});
curl http://localhost:3000/api/todos
You can use swagger-ui-react
to create API Docs automatically.
"use client";
import dynamic from "next/dynamic";
import "swagger-ui-react/swagger-ui.css";
const DynamicSwaggerUI = dynamic(() => import("swagger-ui-react"), {
ssr: false,
loading: () => <p>Loading API Docs...</p>,
});
export function Swagger({ spec }: { spec: Record<string, any> }) {
return <DynamicSwaggerUI spec={spec} />;
}
NextPostgrestSwagger
in a React Server Componentimport { NextPostgrestSwagger } from "next-postgrest";
import { Swagger } from "./_components/swagger";
export default async function Page() {
const spec = await NextPostgrestSwagger({
url: "http://localhost:3333", // your PostgREST endpoint
host: "localhost:3000", // your site
basePath: "/api", // path to your NextPostgrest route handler
});
return <Swagger spec={spec} />;
}
before
You can use before
to inspect the incoming request and return a new Response
.
// app/api/[[...rest]]/route.ts
import { NextPostgrest } from "next-postgrest";
export const { GET, POST, PUT, DELETE, PATCH } = NextPostgrest({
url: "http://postgrest:3333",
basePath: "/api",
before({ pathname, searchParams, view, request }) {
// Validate something
if (Object.keys(searchParams).includes("myField")) {
return new Response(JSON.stringify({ message: "bad request" }), {
status: 400,
});
}
},
});