Skip to content

Latest commit

 

History

History
53 lines (35 loc) · 2.28 KB

README.md

File metadata and controls

53 lines (35 loc) · 2.28 KB

Nextjs Auth Middleware

Current Release Downloads npm

Nextjs-Auth-Middleware is a Node.js package that provides middleware for adding API key authentication to secure an API route in Next.js. This package is based on Next.js middleware, so I invite you to consult the Next.js Middleware documentation.

pages/api/your-api.{ts,js}

Installation

It can be installed via npm, yarn, or pnpm by running one of the following commands:

# Using npm
npm install --save nextjs-auth-middleware@latest

# Using yarn
yarn add nextjs-auth-middleware@latest

# Using pnpm
pnpm add nextjs-auth-middleware@latest

Usage

To use the middleware, import it into your pages/api/your-api.{ts,js} file and pass the request and response objects to it, along with an optional processEnv option to specify the name of the environment variable containing the API key. If the processEnv option is not provided, the default value of API_ROUTE_PUBLIC_KEY will be used.

import NextAuthMiddleware from 'nextjs-auth-middleware';

async function handler(req, res) {
  // Run the auth middleware
  await NextAuthMiddleware(req, res, {
    processEnv: process.env.API_ROUTE_KEY, // optional, default is API_ROUTE_PUBLIC_KEY
  });

  // Rest of the API logic
  res.json({ message: 'Hello NextJs Auth! 🚀' });
}

Remember to set the appropriate environment variable (either the default or the one specified with the processEnv option) with the API key in order for the middleware to function properly.

Keep in touch with me

License

This project is licensed under License.