nextjs-basic-auth-middleware icon indicating copy to clipboard operation
nextjs-basic-auth-middleware copied to clipboard

How to work with nextBasicAuthMiddleware approach?

Open myrkytyn opened this issue 2 years ago • 1 comments

Hello! Need your help with the nextBasicAuthMiddleware approach. I need to have other rules in the middleware function so I'm trying to implement the nextBasicAuthMiddleware function. createNextAuthMiddleware approach works.

How to implement the nextBasicAuthMiddleware function?

Next.JS 13 with App Router.

When I used the nextBasicAuthMiddleware function basic auth didn't work. middleware.ts file in the root of the project

import { NextResponse } from 'next/server';
import { nextBasicAuthMiddleware } from 'nextjs-basic-auth-middleware'

const options = {users: [{ name: "test", password: "test" }]};
export const middleware = (req: any) => {
    nextBasicAuthMiddleware(options, req)
    return NextResponse.next()
}

export const config = {
    matcher: ['/(.*)'],
}

When I used the createNextAuthMiddleware function basic auth worked well.

import { createNextAuthMiddleware } from 'nextjs-basic-auth-middleware'

const options = {users: [{ name: "test", password: "test" }]};
export const middleware = createNextAuthMiddleware(options)

export const config = {
    matcher: ['/(.*)'],
}

What did I do wrong? How can I debug this problem?

myrkytyn avatar Jul 28 '23 20:07 myrkytyn

You need to return the response provided by that function. I think the code sample in the docs is a bit off, although this comment:

Add this middleware after any required work.

Is accurate. This could be a simple use case:

export function middleware(req) {
  // ..perform any other required middleware first

  return nextBasicAuthMiddleware(options, req);
}

To use a matcher:

export function middleware(req) {
  if (someMatcherCondition) {
    return nextBasicAuthMiddleware(options, req);
  }

  return NextResponse.next();
}

atothewest avatar Aug 08 '23 11:08 atothewest