All Projects → storyofams → next-api-decorators

storyofams / next-api-decorators

Licence: MIT license
Collection of decorators to create typed Next.js API routes, with easy request validation and transformation.

Programming Languages

typescript
32286 projects
javascript
184084 projects - #8 most used programming language
CSS
56736 projects
shell
77523 projects

Projects that are alternatives of or similar to next-api-decorators

next-banner
🖼️ Generate Open Graph images for Next.js on build
Stars: ✭ 45 (-75.94%)
Mutual labels:  next, vercel
uniauth-backend
backend service to power uniAuth
Stars: ✭ 16 (-91.44%)
Mutual labels:  backend, nestjs
nestjs-zero-to-hero
Coding through the course: NestJS Zero to Hero - Modern TypeScript Backend Development
Stars: ✭ 23 (-87.7%)
Mutual labels:  backend, nestjs
Bank
🏦 Full Stack Web Application similar to financial software that is used in banking institutions | React.js and Node.js
Stars: ✭ 1,158 (+519.25%)
Mutual labels:  backend, nestjs
nestjs-config
NestJS Module for Nonfig services. Nonfig combines Configurations and Features. So you change features, and release swiftly, and measure to digital impact.
Stars: ✭ 40 (-78.61%)
Mutual labels:  backend, nestjs
Nest User Auth
A starter build for a back end which implements managing users with MongoDB, Mongoose, NestJS, Passport-JWT, and GraphQL.
Stars: ✭ 145 (-22.46%)
Mutual labels:  backend, nestjs
next-api-og-image
Easy way to generate open-graph images dynamically in HTML or React using Next.js API Routes. Suitable for serverless environment.
Stars: ✭ 179 (-4.28%)
Mutual labels:  next, vercel
parse-react
[EXPERIMENTAL] React, React Native, and React with SSR (e.g. Next.js) packages to interact with Parse Server backend
Stars: ✭ 58 (-68.98%)
Mutual labels:  backend, next
personal-website
Personal website – made with Next.js, Preact, MDX, RMWC, & Vercel
Stars: ✭ 16 (-91.44%)
Mutual labels:  next, vercel
bradgarropy.com
🏠 my home on the web
Stars: ✭ 58 (-68.98%)
Mutual labels:  next, vercel
Ultimate Backend
Multi tenant SaaS starter kit with cqrs graphql microservice architecture, apollo federation, event source and authentication
Stars: ✭ 978 (+422.99%)
Mutual labels:  backend, nestjs
Bear-Blog-Engine
Modern blog engine made with Go and the Next.js framework
Stars: ✭ 23 (-87.7%)
Mutual labels:  backend, vercel
Nestjs-Typeorm-Auth
NestJS + Typeorm codebase containing a full authentification system with roles, sessions and email verification.
Stars: ✭ 37 (-80.21%)
Mutual labels:  backend, nestjs
Plumier
A TypeScript backend framework focuses on development productivity, uses dedicated reflection library to help you create a robust, secure and fast API delightfully.
Stars: ✭ 223 (+19.25%)
Mutual labels:  backend, decorators
bad-cards-game
Bad Cards Game
Stars: ✭ 23 (-87.7%)
Mutual labels:  backend, nestjs
iron-session
🛠 Node.js stateless session utility using signed and encrypted cookies to store data. Works with Next.js, Express, NestJs, Fastify, and any Node.js HTTP framework.
Stars: ✭ 1,729 (+824.6%)
Mutual labels:  next, nestjs
nest-auth-example
Nest.js authentication with Passport. Realworld example
Stars: ✭ 186 (-0.53%)
Mutual labels:  backend, nestjs
personal-website
My personal website, statically generated by Next.js
Stars: ✭ 16 (-91.44%)
Mutual labels:  next, vercel
Mastering-PHP7
📚 PinterCoding University. Author : Gun Gun Febrianza
Stars: ✭ 92 (-50.8%)
Mutual labels:  backend
ctrl-v
📋 a modern, open-source pastebin with latex and markdown rendering support
Stars: ✭ 93 (-50.27%)
Mutual labels:  vercel
Story of AMS

@storyofams/next-api-decorators


A collection of decorators to create typed Next.js API routes, with easy request validation and transformation.

View docs


Basic usage

// pages/api/user.ts
class User {
  // GET /api/user
  @Get()
  async fetchUser(@Query('id') id: string) {
    const user = await DB.findUserById(id);

    if (!user) {
      throw new NotFoundException('User not found.');
    }

    return user;
  }

  // POST /api/user
  @Post()
  @HttpCode(201)
  async createUser(@Body(ValidationPipe) body: CreateUserDto) {
    return await DB.createUser(body.email);
  }
}

export default createHandler(User);

💡 Read more about validation here

The code above without next-api-decorators
export default async (req: NextApiRequest, res: NextApiResponse) => {
  if (req.method === 'GET') {
    const user = await DB.findUserById(req.query.id);
    if (!user) {
      return res.status(404).json({
        statusCode: 404,
        message: 'User not found'
      })
    }

    return res.json(user);
  } else if (req.method === 'POST') {
    // Very primitive e-mail address validation.
    if (!req.body.email || (req.body.email && !req.body.email.includes('@'))) {
      return res.status(400).json({
        statusCode: 400,
        message: 'Invalid e-mail address.'
      })
    }

    const user = await DB.createUser(req.body.email);
    return res.status(201).json(user);
  }

  res.status(404).json({
    statusCode: 404,
    message: 'Not Found'
  });
}

Motivation

Building serverless functions declaratively with classes and decorators makes dealing with Next.js API routes easier and brings order and sanity to your /pages/api codebase.

The structure is heavily inspired by NestJS, which is an amazing framework for a lot of use cases. On the other hand, a separate NestJS repo for your backend can also bring unneeded overhead and complexity to projects with a smaller set of backend requirements. Combining the structure of NestJS, with the ease of use of Next.js, brings the best of both worlds for the right use case.

If you are not familiar with Next.js or NestJS and want some more information (or need to be convinced), check out the article Awesome Next.js API Routes with next-api-decorators by @tn12787

Installation

Visit https://next-api-decorators.vercel.app/docs/#installation to get started.

Documentation

Refer to our docs for usage topics:

Validation

Route matching

Using middlewares

Custom middlewares

Pipes

Exceptions

Available decorators

Class decorators

Description
@SetHeader(name: string, value: string) Sets a header name/value into all routes defined in the class.
@UseMiddleware(...middlewares: Middleware[]) Registers one or multiple middlewares for all the routes defined in the class.

Method decorators

Description
@Get(path?: string) Marks the method as GET handler.
@Post(path?: string) Marks the method as POST handler.
@Put(path?: string) Marks the method as PUT handler.
@Delete(path?: string) Marks the method as DELETE handler.
@Patch(path?: string) Marks the method as PATCH handler.
@SetHeader(name: string, value: string) Sets a header name/value into the route response.
@HttpCode(code: number) Sets the http code in the route response.
@UseMiddleware(...middlewares: Middleware[]) Registers one or multiple middlewares for the handler.

Parameter decorators

Description
@Req() Gets the request object.
@Res()* Gets the response object.
@Body() Gets the request body.
@Query(key: string) Gets a query string parameter value by key.
@Header(name: string) Gets a header value by name.
@Param(key: string) Gets a route parameter value by key.

* Note that when you inject @Res() in a method handler you become responsible for managing the response. When doing so, you must issue some kind of response by making a call on the response object (e.g., res.json(...) or res.send(...)), or the HTTP server will hang.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].