Gathering detailed insights and metrics for @oriun/next-api
Gathering detailed insights and metrics for @oriun/next-api
Gathering detailed insights and metrics for @oriun/next-api
Gathering detailed insights and metrics for @oriun/next-api
npm install @oriun/next-api
Typescript
Module System
Node Version
NPM Version
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
NextJS API Wrapper is a powerful NPM package that enables developers to create wrappers around their NextJS API routes. It provides request parsing with Zod, middleware, and error handlers, simplifying the process of setting up and managing your API routes. It is also compatible with decorators, allowing you to create API routes with classes, and supports NodeJs and Edge runtimes.
To install the NextJS API Wrapper, use the following command:
1pnpm install @oriun/next-api
NextJS API Wrapper makes it easy to create and manage your API routes. Here's how to use it:
First, import the api
wrapper and create a Zod
schema to parse and validate your requests. You can provide schemas for the body
, query
, cookies
and params
properties of the request:
1import { api } from "@oriun/next-api"; 2import { z } from "zod"; 3 4const body = z.object({ 5 name: z.string().min(1).max(100), 6});
Next, create a function that handles your API route and wrap it with the api
wrapper:
1export const GET = api((_ctx, _req) => { 2 return "Hello world !"; 3}, { body }) 4 5export const POST = api((ctx) { 6 return { message: 'Nice to meet you ' + ctx.body.name + '!' }; 7}, { body })
NextJS API Wrapper also supports decorators, allowing you to create API routes with classes. To create the same endpoints as above, first import the API
decorator and create a Zod
schema to parse and validate your requests:
1import { API } from "@oriun/next-api"; 2import { z } from "zod"; 3 4const body = z.object({ 5 name: z.string().min(1).max(100), 6});
Next, create a Route class with HTTP methods as method names:
1class Route { 2 @API() 3 async GET() { 4 return { message: "Hello world !" }; 5 } 6 7 @API({ body }) 8 async POST(variables: any) { 9 const { name } = variables.body as z.infer<typeof body>; 10 return { message: "Nice to meet you " + name + "!" }; 11 } 12}
Finally, export the methods:
1export const { GET, POST } = new Route();
In this example, we've created a simple API route that responds to GET and POST requests. The GET request returns a simple greeting, while the POST request expects a body with a name
property and returns a personalized greeting.
NextJS API Wrapper provides a number of options to customize your API routes. Here's how to use them:
NextJS API Wrapper supports middleware, allowing you to run code before your API routes. To use middleware, simply pass an array of middleware functions to the api
wrapper:
1import { createAPI } from "@oriun/next-api"; 2 3function checkAuth(_ctx: unknown, req: Request) { 4 const authorization = req.headers.get("Authorization"); 5 if (!authorization) { 6 throw new Response(JSON.stringify({ message: "Unauthorized" }), { 7 status: 401, 8 }); 9 } 10 return { authorization }; 11} 12 13const authenticatedRoute = createAPI({ 14 middlewares: [checkAuth], 15}); 16 17export const GET = authenticatedRoute((ctx, _req) => { 18 return `Hello world user ${ctx.authorization}!`; 19}); 20 21const body = z.object({ 22 name: z.string().min(1).max(100), 23}); 24export const POST = authenticatedRoute( 25 (ctx, _req) => { 26 return `User ${ctx.authorization} created resource with name ${ctx.body.name}!`; 27 }, 28 { body } 29);
As you can see, the middleware function receives the ctx
and req
objects as parameters. The ctx
object contains the parsed request body, query, cookies and params, while the req
object contains the original request.
The middleware function can return an object that will be merged with the ctx
object, allowing you to pass data to your API route. If the middleware function throws an error, the error will be handled by the error handlers. If the middleware function returns a response, the response will be returned by the API route.
NextJS API Wrapper supports error handling, allowing you to handle errors thrown by your API routes. To use error handling, simply pass an array of error handler functions to the api
wrapper:
1import { createAPI } from "@oriun/next-api";
2
3function errorHandler(error: any) {
4 if (error instanceof Error) {
5 return new Response(JSON.stringify({ message: error.message }), {
6 status: 500,
7 });
8 }
9 return new Response(
10 JSON.stringify({ message: "Unexpected", details: error }),
11 {
12 status: 500,
13 }
14 );
15}
16
17const errorHandledRoute = createAPI({
18 errorHandlers: [errorHandler],
19});
20
21export const GET = errorHandledRoute((_ctx, _req) => {
22 throw new Error("Something went wrong");
23});
As you can see, the error handler function receives the error as a parameter. The error can be an Error
object or any other type of variable.
The error handler function can return a response, allowing you to return a custom error response. If the error handler function returns a response, the response will be returned by the API route. If the error handler function returns nothing, the error will be rethrown and handled by the next error handler.
You can also use middleware and error handlers with decorators. To do so, simply pass an array of middleware functions and error handler functions to the createAPIDecorator
decorator:
1import { createAPIDecorator } from "@oriun/next-api"; 2 3function checkAuth(_ctx: unknown, req: Request) { 4 const authorization = req.headers.get("Authorization"); 5 if (!authorization) { 6 throw new Response(JSON.stringify({ message: "Unauthorized" }), { 7 status: 401, 8 }); 9 } 10 return { authorization }; 11} 12 13function errorHandler(error: any) { 14 if (error instanceof Error) { 15 return new Response(JSON.stringify({ message: error.message }), { 16 status: 500, 17 }); 18 } 19 return new Response( 20 JSON.stringify({ message: "Unexpected", details: error }), 21 { 22 status: 500, 23 } 24 ); 25} 26 27const api = createAPIDecorator({ 28 middlewares: [checkAuth], 29 errorHandlers: [errorHandler], 30}); 31 32const body = z.object({ 33 name: z.string().min(1).max(100), 34}); 35 36class Route { 37 @api() 38 async GET() { 39 return `Hello world user ${this.authorization}!`; 40 } 41 42 @api({ body }) 43 async POST(variables: any) { 44 return `User ${this.authorization} created resource with name ${this.body.name}!`; 45 } 46} 47 48export const { GET, POST } = new Route();
api(handler, schemas?, errorHandlers?)
The api function is used to create an API route. Here's an example of how to use it:
1import { api } from "@oriun/next-api"; 2import { z } from "zod"; 3 4const body = z.object({ 5 name: z.string().min(1).max(100), 6}); 7 8async function handler(variables: any) { 9 const { name } = variables.body as z.infer<typeof body>; 10 return { message: "Nice to meet you " + name + "!" }; 11} 12 13export const POST = api(handler, { body });
createAPI({ middlewares, errorHandlers })
The createAPI function is used to create an API with pre-configured middleware. Here's an example of how to use it:
1import { createAPI } from "@oriun/next-api"; 2import { z } from "zod"; 3 4export function firstMiddleware() { 5 console.log("firstMiddleware"); 6 return {}; 7} 8 9const body = z.object({ 10 name: z.string().min(1).max(100), 11}); 12 13async function handler(variables: any) { 14 const { name } = variables.body as z.infer<typeof body>; 15 return { message: "Nice to meet you " + name + "!" }; 16} 17 18export const POST = createAPI({ middlewares: [firstMiddleware] })(handler, { 19 body, 20});
API(schemas?, errorHandlers?)
The API decorator is used to create an API route. Here's an example of how to use it:
1import { API } from "@/lib"; 2import { z } from "zod"; 3 4const body = z.object({ 5 name: z.string().min(1).max(100), 6}); 7 8class Route { 9 @API({ body }) 10 async POST(variables: any) { 11 const { name } = variables.body as z.infer<typeof body>; 12 return { message: "Nice to meet you " + name + "!" }; 13 } 14} 15 16export const { POST } = new Route();
createAPIDecorator({ middlewares, errorHandlers })
The createAPIDecorator function is used to create a custom API decorator with pre-configured middleware. Here's an example of how to use it:
1import { createAPIDecorator } from "@oriun/next-api"; 2 3export function firstMiddleware() { 4 console.log("firstMiddleware"); 5 return {}; 6} 7 8const customApi = createAPIDecorator({ middlewares: [firstMiddleware] }); 9 10class Route { 11 @customApi() 12 async GET() { 13 return { message: "Hello world!" }; 14 } 15} 16 17export const { GET } = new Route();
Contributions are always welcome! Here's how you can help:
Before contributing, please read our Code of Conduct.
This project is licensed under the MIT License. See the LICENSE file for details.
The MIT License is a permissive open source license that is well-suited to many types of projects. If you choose to use it, you'll need to include a copy of the MIT License in your project. If you prefer a different license, you'll need to include that instead.
No vulnerabilities found.
No security vulnerabilities found.