A chainable router designed for Next.js api. inspired and regex based from itty-router

Overview

Next.js Api Router

A chainable router designed for Next.js api. inspired and regex based from itty-router

Features

  • Tiny (~8xx bytes compressed) with zero dependencies.
  • Strong typing with typescript also javascript with VSCode
  • Anything is async/await handler
  • Route params, with wildcards and optionals (e.g. /base/:collection/:id?)
  • Middleware support
  • By default error handler response is json
  • Support anything of HTTP methods
  • Chainable route declarations
  • No dependencies

Installation

npm i @arisris/next-api-router

Example Usage

res.status(500).send("Internal Server Error") // By default handled with json response }) .all("*", async () => true) // middleware should return true .get("/hello", async (_, res) => res.send("Hello World")) // simple .get( "/wait", async () => await new Promise((resolve) => setTimeout(resolve, 3000)), // wait for 3000ms async (_, res) => res.json({ msg: "Done..." }) ) .get("/error", async () => { throw new Error("OMG!"); }) .get("/timeout", async () => { // No response is considered timeout }) .get("/user/:name?", async (req, res) => res.json({ params: req.params })) // not found .all("*", async (_, res) => res.status(404).send("Not Found")) .handle; // Final handler of NextApiHandler">
// file: pages/api/[...any].ts
import NextApiRoute from "@arisris/next-api-router";

export default NextApiRoute({
  key: "all", // a rest params default to "any"
  timeout: 5000, // timeout in ms default to 10000ms
  //onError: (error, req, res) => res.status(500).send("Internal Server Error") // By default handled with json response
})
  .all("*", async () => true) // middleware should return true
  .get("/hello", async (_, res) => res.send("Hello World")) // simple
  .get(
    "/wait",
    async () => await new Promise((resolve) => setTimeout(resolve, 3000)), // wait for 3000ms
    async (_, res) => res.json({ msg: "Done..." })
  )
  .get("/error", async () => {
    throw new Error("OMG!");
  })
  .get("/timeout", async () => {
    // No response is considered timeout
  })
  .get("/user/:name?", async (req, res) => res.json({ params: req.params }))
  // not found
  .all("*", async (_, res) => res.status(404).send("Not Found"))
  .handle; // Final handler of NextApiHandler

Todo better documentation

--

Links

My Website itty-router

You might also like...

Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

Jan 3, 2023

microregex is an open source and highly curated catalog of regular expression patterns. It offers programmers RegEx snippets that can be quickly exported into a variety of programming languages and distributed around teams.

microregex is an open source and highly curated catalog of regular expression patterns. It offers programmers RegEx snippets that can be quickly exported into a variety of programming languages and distributed around teams.

microregex - A catalog of RegEx patterns View Demo · Report Bug · Request Feature Loved the tool? Please consider contributing ✍️ to help it improve!

Oct 25, 2022

easier than regex string matching patterns for urls and other strings. turn strings into data or data into strings.

url-pattern easier than regex string matching patterns for urls and other strings. turn strings into data or data into strings. This is a great little

Jan 5, 2023

🎨 Regex visualizer & editor

🎨 Regex visualizer & editor

Regex-Vis 🎨 Regex visualizer & editor Preview Features Regular expression visualizer Visual editing regular expression Testing regular expression Blo

Dec 31, 2022

This package is for developers to be able to easily integrate bad word checking into their projects.\r This package can return bad words in array or regular expression (regex) form.

Vietnamese Bad Words This package is for developers to be able to easily integrate bad word checking into their projects. This package can return bad

Nov 3, 2022

Fiz uma validação de senhas no Front-End usando RegEx!

Fiz uma validação de senhas no Front-End usando RegEx!

Seja bem vindo a um dos meus #JokeCodes Nesse código vou te mostrar como fazer uma validação de senha no Front-End, com feedback na tela de login!, us

Oct 5, 2022

🛣️ A tiny and fast http request router designed for use with deno and deno deploy

Rutt Rutt is a tiny http router designed for use with deno and deno deploy. It is written in about 200 lines of code and is pretty fast, using an exte

Dec 10, 2022

Router JS 💽 Simple Router building in JavaScript

Router JS 💽 Simple Router building in JavaScript

Feb 12, 2022

🍉 Water is a micro-ORM + QueryBuilder designed to facilitate queries and operations on PostgreSQL databases designed to work in Melon

🍉 Water Water is a micro-ORM + QueryBuilder designed to facilitate queries and operations on PostgreSQL databases designed to work in MelonRuntime In

Aug 6, 2022

Facile is an HTML form validator that is inspired by Laravel's validation style and is designed for simplicity of use.

Facile is an HTML form validator that is inspired by Laravel's validation style and is designed for simplicity of use.

Facile is an HTML form validator that is inspired by Laravel's validation style and is designed for simplicity of use.

Dec 26, 2022

A Weather API project inspired by The Ultimate API Challenge / Weather API.

Weather API Project A Weather API project inspired by The Ultimate API Challenge / Weather API. Tech Stack: React.js Tailwind Axios Inspiration The Pr

Dec 29, 2021

Angular 14 JWT Authentication & Authorization with Web API and HttpOnly Cookie - Token Based Auth, Router, Forms, HttpClient, BootstrapBootstrap

Angular 14 JWT Authentication & Authorization with Web API and HttpOnly Cookie - Token Based Auth, Router, Forms, HttpClient, BootstrapBootstrap

Angular 14 JWT Authentication with Web API and HttpOnly Cookie example Build Angular 14 JWT Authentication & Authorization example with Web Api, HttpO

Dec 26, 2022

Next.js and Apollo-Client web application, designed for learning and real-world applicability.

Next.js and Apollo-Client web application, designed for learning and real-world applicability.

NextJs Apollo Boilerplate Boilerplate for building applications using Next.js and Apollo This boilerplate is made for those who want to start a new pr

Sep 4, 2022

This Next.js app is designed to be used with the Figment Learn Pathways, to help developers learn about various blockchain protocols such as Solana, NEAR, Secret, Polygon and Polkadot!

This Next.js app is designed to be used with the Figment Learn Pathways, to help developers learn about various blockchain protocols such as Solana, NEAR, Secret, Polygon and Polkadot!

👋🏼 What is learn-web3-dapp? We made this decentralized application (dApp) to help developers learn about Web 3 protocols. It's a Next.js app that us

Oct 1, 2022

Bun-Bakery is a web framework for Bun. It uses a file based router in style like svelte-kit. No need to define routes during runtime.

Bun-Bakery is a web framework for Bun. It uses a file based router in style like svelte-kit. No need to define routes during runtime.

Bun Bakery Bun-Bakery is a web framework for Bun. It uses a file based router in style like svelte-kit. No need to define routes during runtime. Quick

Dec 6, 2022

An example application that uses file-based routing with Angular, Analog, Vite with the Angular Router

Angular, Vite, and File-based routes This is an example application that uses Angular, Analog, and Vite for file-based routing. Routes are places in t

Sep 25, 2022

Aleph.js is a fullstack framework in Deno, inspired by Next.js.

Aleph.js is a fullstack framework in Deno, inspired by Next.js.

Dec 30, 2022

MSN Redesign made with Next - Inspired by Igor Monteiro's Layout

MSN Redesign made with Next - Inspired by Igor Monteiro's Layout

MSN Redesign 🏳 Made with Next - Inspired by Igor Monteiro's Layout | Behance 🛠️ Stack Next React Yarn (v1.22.17) CSS in JS CSS - Gradient Responsive

Feb 16, 2022
Owner
Aris Riswanto
Senior Web Developer | Jamstack | Node.js | React.js | Next.js | Tailwind.css | Web project architect
Aris Riswanto
a tiny and isomorphic URL router for JavaScript

Synopsis Director is a router. Routing is the process of determining what code to run when a URL is requested. Motivation A routing library that works

a decoupled application framework 5.6k Dec 28, 2022
A navigation aid (aka, router) for the browser in 850 bytes~!

A navigation aid (aka, router) for the browser in 865 bytes~! Install $ npm install --save navaid Usage const navaid = require('navaid'); // Setup r

Luke Edwards 732 Dec 27, 2022
An Express.js-Style router for the front-end

An Express.js-Style router for the front-end. Code the front-end like the back-end. Same language same framework. frontexpress demo import frontexpres

Camel Aissani 262 Jul 11, 2022
Single Page Application micro framework. Views, routes and controllers in 60 lines of code

SPApp Single Page Application Micro Framework Supports views, controllers and routing in 60 lines of code! Introduction If you heard anything about MV

Andrew 262 Nov 23, 2022
Dead-simple CORS handling for any itty-router API (test with Cloudflare Workers, but works anywhere)!

Simple CORS-handling for any itty-router API. Designed on Cloudflare Workers, but works anywhere. Features Tiny. Currently ~600 bytes, with zero-depen

Kevin R. Whitley 6 Dec 16, 2022
Cloudflare Durable Objects + Itty Router = shorter code

TLDR; Cloudflare Durable Objects + Itty Router = much shorter code Features Removes nearly all boilerplate from Durable Objects Run instance methods d

Kevin R. Whitley 156 Jan 4, 2023
Micro client-side router inspired by the Express router

Tiny Express-inspired client-side router. page('/', index) page('/user/:user', show) page('/user/:user/edit', edit) page('/user/:user/album', album) p

Sloth 7.6k Dec 28, 2022
An itty library to handle common time-related things for your API needs.

Tiny (~500 bytes) time math library for making date handling and TTLs within your APIs beautiful. Features Tiny @ ~500 bytes gzipped total, and tree-s

Kevin R. Whitley 8 Jan 2, 2023
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022