New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More

next-pipe-middleware

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

next-pipe-middleware

This is a library for building Next.js middleware declaratively. You can create highly readable and manageable middleware by piping multiple functions together.

  • 1.0.0
  • npm
  • Socket score

Version published
Maintainers
1
Created

🧵 Next Pipe Middleware

This is a library for building Next.js middleware declaratively. You can create highly readable and manageable middleware by piping multiple functions together.

🌟 Features

  • Multiple middleware executions in series
  • Conditional execution of middleware
  • Middleware processes that can be terminated midstream

🔏 Requirements

Next.js v12.2.0+ (Middleware support)

🐈 Usage

Basic

Pass NextRequest, NextResponse, and arrays of multiple middleware to pipeMiddleware function.

export default async function middleware(req: NextRequest) {
  return pipeMiddleware(req, NextResponse.next(), [
    fooMiddleware,
    barMiddleware,
    hogeMiddleware,
  ])
}

Each middleware function (PipeableMiddleware) differs from the Next.js middleware functions only in that it takes a NextResponse as its second argument:

const fooMiddleware: PipeableMiddleware = async (req, res) => {
  res.cookies.set('foo', 'bar')
  return res;
};

Conditional middleware

If you want to control execution of middleware according to the page path, pass an object containing a matcher function as the second element of the tuple

export default async function middleware(req: NextRequest) {
  return pipeMiddleware(req, NextResponse.next(), [
    basicAuthMiddleware,
    [redirectMiddleware, {matcher: (path) => path.startsWith('/secret')}],
    [refreshTokenMiddleware, {matcher: (path) => path.startsWith('/my')}],
  ])
}

Terminable middleware

If you want to terminate the entire process on a particular piece of middleware (i.e., you do not want subsequent pieces of middleware to run), change the response format as follows

const basicAuth: PipeableMiddleware = async (req, res) => {
  const success = validateBasicAuth(req);
  if (success) {
    return res;
  } else {
    return {
      res: NextResponse.rewrite(/**/),
      final: true,
    }; // terminate process after this middleware by returning object with `final: true` and `res`
  }
};

export default async function middleware(req: NextRequest) {
  return pipeMiddleware(req, NextResponse.next(), [
    basicAuthMiddleware, // if basic auth failed, the process ends here.
    redirectMiddleware,
    refreshTokenMiddleware
  ])
}

📖 Appendix

Demo

Motivation

If you want to implement the following at the middleware file:

  • Applying Basic-auth, if it fails, terminates at that point.
  • If user access to specific page, redirect and terminates at that point.
  • Refresh the authentication token.

Without this library, you would have to write codes like this:

export default async function middleware(req: NextRequest) {
  const res = NextResponse.next()
  const success = await basicAuthMiddleware(req, res);
  if (!success) {
    return res;
  }

  if (req.url.startsWith('/secret')) {
    const [shouldRedirect, redirectRes] = await redirectMiddleware(req, res);
    if (shouldRedirect) {
      return redirectRes;
    }
  }

  if (req.url.startsWith('/my')) {
    await refreshTokenMiddleware(req, res);
  }
  return res;
}

It is difficult to know what kind of process the middleware consists of, because it is necessary to check whether the process should be terminated depending on the response, or whether it should be executed according to the path, etc.

This library allows you to write what you want to do declaratively and readably as above.

FAQs

Package last updated on 18 Jul 2022

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts