0.0.2 • Published 5 years ago

@spalger/next-plus v0.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
5 years ago

@spalger/next-plus

A couple helpers for working with next.js

Routing

createNextHandler

Create a next.js handler, which is just a micro handler that takes NextRoute objects instead. NextRoute objects are just Route objects that don't specify their path, since next.js handles routing via the file-system.

Signature:

interface Options {
  routes: NextRoute[],

  /**
   * global request handler that can return a response to take over requests
   */
  onRequest?: (ctx: ReqContext) => Promise<RouteResponse | void> | RouteResponse | void,

  /**
   * Array of exact origin header values that will authorize cors pre-flight requests
   */
  corsAllowOrigins?: string[]

  /**
   * Object with methods that will be called while a request is processed, see `./src/hooks.ts`
   */
  hooks?: Hooks
}

function createNextHandler(options: Options | NextRoute[]): (req: IncomingMessage, res: ServerResponse) => void

Example:

import { createNextHandler, assertValidJwtAuthrorization, getConfigVar } from '@spalger/next-plus'

module.exports = createNextHandler({
  onRequest(ctx) {
    assertValidJwtAuthrorization(ctx, getConfigVar('JWT_SECRET'))
  },

  routes: [
    new NextRoute('GET', (ctx) => ({
      status: 200,
      body: 'bar'
    }))
  ],
})

NextRoute

Signature:

new NextRoute(
  // valid request method for this route
  method: string,
  // function to execute when requests are received
  handler: (ctx: ReqContext) => Promise<RouteResponse> | RouteResponse,
)

Simplified version of Route for use with next.js dynamic routing.

ReqContext

See @spalger/micro-plus ReqContext docs

RouteResponse

See @spalger/micro-plus RouteResponse docs

Errors

See @spalger/micro-plus "Errors" docs

Config

See @spalger/micro-plus "Config" docs

JWT

See @spalger/micro-plus "JWT" docs

Search Params

See @spalger/micro-plus "Search Params" docs