npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@vdtn359/next-connect

v1.0.0

Published

The method routing and middleware layer for Next.js (and several others)

Downloads

3

Readme

next-connect

npm install size CircleCI codecov PRs Welcome

The method routing and middleware layer for Next.js (also works in micro or Node.js HTTP Server). Powered by trouter.

Installation

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

Usage

next-connect is often used in API Routes:

// pages/api/index.js
import nextConnect from "next-connect";

const handler = nextConnect();

handler
  .use(someMiddleware())
  .get((req, res) => {
    res.send("Hello world");
  })
  .post((req, res) => {
    res.json({ hello: 'world' });
  });

export default handler;

For usage in pages with getServerSideProps, see .apply.

See an example in nextjs-mongodb-app (CRUD, Authentication with Passport, and more)

API

The API is similar to Express.js with several differences.

nextConnect(options)

Initialize an instance of next-connect.

options.onError

Accepts a function as a catch-all error handler; executed whenever a middleware throws an error. By default, it responses with status code 500 and error message if any.

function onError(err, req, res, next) {
  logger.log(err);

  res.status(500).end(err.toString());
  // OR: you may want to continue
  next()
}

const handler = nextConnect({ onError });

handler
  .use((req, res, next) => {
    throw new Error('oh no!');
    // or use next
    next(Error('oh no'));
  })
  .use((req, res) => {
    // this will run if next() is called in onError
    res.end('error no more');
  });

options.onNoMatch

Accepts a function of (req, res) as a handler when no route is matched. By default, it responses with 404 status and not found body.

function onNoMatch(req, res) {
  res.status(404).end('page is not found... or is it')
}

const handler = nextConnect({ onNoMatch });

.use(base, ...fn)

base (optional) - match all route to the right of base or match all if omitted. fn(s) are functions of (req, res[, next]) or an instance of next-connect, where it will act as a sub application.

handler.use((req, res, next) => {
  req.hello = 'world';
  // call next if you want to proceed to next in chain
  next();
});

// Reuse an instance of nextConnect
const anotherHandler = nextConnect()
anotherHandler.use(commonFn).use(anotherFn);
handler.use(anotherHandler);

// You can use a library too.
handler.use(passport.initialize());

.METHOD(pattern, ...fns)

METHOD is a HTTP method (GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE) in lowercase. pattern (optional) - match all route based on supported pattern or match all if omitted. fn(s) are functions of (req, res[, next]). This is ideal to be used in API Routes.

handler.use('/user', passport.initialize());
handler.get('/user', (req, res, next) => {
  res.json(req.user);
});
handler.post('/users', (req, res, next) => {
  res.end('User created');
});
handler.put('/user/:id', (req, res, next) => {
  // https://nextjs.org/docs/routing/dynamic-routes
  res.end(`User ${req.query.id} updated`);
});
handler.get((req, res, next) => {
  res.end('This matchs whatever route')
})

However, since Next.js already handles routing (including dynamic routes), we often omit pattern in .METHOD.

.apply(req, res)

Applies the middleware and returns a promise after which you can use the upgraded req and res.

This can be useful in getServerSideProps.

// page/index.js
export async function getServerSideProps({ req, res }) {
  const handler = nextConnect();
  handler.use(passport.initialize());
  try {
    await handler.apply(req, res);
  } catch(e) {
    // handle the error
  }
  // do something with the upgraded req and res
  return {
    props: { user: req.user }, // will be passed to the page component as props
  }
};

Using in other frameworks

next-connect supports any frameworks that has the signature of (req, res).

Micro

const {send} = require('micro')
const handler = require('next-connect')()

handler
  .use(someMiddleware())
  .get(() => 'hello world')
  .post((req, res) => {
    send(res, 200, { hello: 'world' })
  });

module.exports = handler;

Node.js HTTP Server

const handler = require('next-connect')()
const http = require('http');

handler
  .use(someMiddleware())
  .get((req, res) => {
    res.send("Hello world");
  })
  .post((req, res) => {
    res.json({ hello: 'world' });
  });

http.createServer(handler).listen(PORT);

Contributing

Please see my contributing.md.

License

MIT