Skip to content
The method routing and middleware layer for Next.js
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Type Name Latest commit message Commit time
Failed to load latest commit information.
.circleci Add Test and CircleCI (#1) Oct 14, 2019
lib Fix next-connect fail to work if multiple instances are used Nov 17, 2019
.editorconfig 🎉 Initial commit Oct 14, 2019
.gitignore 0.5.1 Nov 17, 2019 🎉 Initial commit Oct 14, 2019


npm minified size CircleCI codecov PRs Welcome

The method routing and middleware layer for Next.js.


npm install next-connect
// or
yarn add next-connect


The usage is similar to Express.js but without path as the first argument.

In API Routes, when doing export default, use handler.

import nextConnect from 'next-connect';

const handler = nextConnect();

//  use middleware

//  response to GET
handler.get(function (req, res) {
    res.send('Hello world');

//  response to POST (req, res) {
    res.json('Hi there');

//  export using handler
export default handler;

Use middleware

Middleware is the core of next-connect. Middlewares are added as layers of a "stack" where the request and response will be routed through each layer one-by-one as long as next() is called.

handler.use(fn[, fn ...])

fn(s) are functions of (req, res[, next]).

handler.use(function (req, res, next) {
    //  Do some stuff with req and res here
    req.user = getUser(req);
    //  Call next() to proceed to the next middleware in the chain

handler.use(function (req, res) {
    if (req.user) res.end(`The user is ${}`);
    else res.end('There is no user');
    //  next() is not called, the chain is terminated.

//  You can use a library too.

//  You can chain them too
handler.use(thisMiddleware, thatMiddleware);

Error middleware

Error middlewares will be called when an error is thrown. They should be placed at the end.

Middlewares that are not error handler will be skipped over. It is not neccessary for the former middleware to call next(). Calling next(new Error()) will also trigger error middleware.

Error middleware is similar to regular middleware except an additional err as the first argument.

handler.get(function (req, res) {
    throw new Error('Oh no!');

handler.use(function (err, req, res, next) {
    res.status(500).end('Internal Server Error');
    //  Pass along the error to another error handler
handler.use(function (err, req, res, next) {

Notice that an error middleware must have four arguments. In case you do not want to have the next argument, use handler.error(fn[, fn ...]) instead.

//  This is still considered an error middleware
handler.error(function (err, res, res) {

Reuse middleware

An instance of NextConnect may be reused.

//  middleware/commonMiddleware.js
import nextConnect from 'next-connect'

const middleware = nextConnect();


export default middleware;

After exporting the instance of nextConnect, import it everywhere you need to reuse.

//  api/boring.js
import commonMiddleware from '../middleware/commonMiddleware';

const handler = nextConnect();
//  reuse the instance

//  extend the reused middleware

Method routing

handler.METHOD(fn[, fn ...])

Response to the HTTP request based on METHOD, where METHOD is the HTTP method (GET, POST, PUT, etc.) in lowercase. (ex., handler.put, ...)

fn is a function of (req, res[, next]).

//  api/publicRoute.js (req, res) {
    res.send('A public route');

The function can also accept more than one argument (function), in which case it will act as a series of middleware.

//  api/privateRoute.js
function isAuth(req, res, next) {
    if (!req.user) res.status(401).end('You need to be authenticated');
    else next();
}, function (req, res) {


If no response is sent, next-connect will return 404.

//  api/somePostRoute (req, res) {

export default handler;

//  Navigating to /api/somePostRoute in the browser will render 404.

Document middleware and getInitialProps

To use next-connect in document middleware or getInitialProps, use (await) handler.apply(req, res) instead.

// page/_document.js
export async function middleware({req, res}: PageContext) {
    const handler = nextConnect();
    // await calling .apply
    await handler.apply(req, res);

// OR
// page/somePage.js
Page.getInitialProps = async ({ req, res }) => {
  const handler = nextConnect();
  await handler.apply(req, res);
  return { ...whatEverYourLittleDesires }

404 automatic response will not be triggered in .apply()


Please see my



You can’t perform that action at this time.