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

Not working with latest next 13

Open suil opened this issue 2 years ago • 5 comments

Somehow it's not working with latest project structure that are generated by npx create-next-app@latest

suil avatar Jun 22 '23 15:06 suil

@suil works for me, what's your middleware.ts like? I just copied the one from examples.

echeng8 avatar Jul 09 '23 19:07 echeng8

Error: The Edge Function "middleware" is referencing unsupported modules: 22:55:26.396 | - next: stream, fs, url, path

// middleware.js
import { createNextAuthMiddleware } from 'nextjs-basic-auth-middleware'

export const middleware = createNextAuthMiddleware(options)

export const config = {
    matcher: ['/(.*)'], // Replace this with your own matcher logic
}

"nextjs-basic-auth-middleware": "^3.1.0",

phsantiago avatar Jul 26 '23 20:07 phsantiago

@phsantiago Did you declare options? What version of Next.JS you are using?

const options = {
  users: [{ name: "username", password: "password" }],
};

myrkytyn avatar Jul 29 '23 11:07 myrkytyn

@myrkytyn sorry, I deleted the repo, so I'm not sure about the version, I think it was 13.4 because was a brand new installation. I did not declare options.

I could make it work but with a different implementation in another repo:

"next": "12.2.12",

//middleware.js
import { NextResponse } from "next/server";

import checkBasicAuth from "@utils/middleware/checkBasicAuth";

export function middleware(request) {
  if (
    !checkBasicAuth(request.headers.get("authorization"), {
      username: process.env.AUTH_USERNAME,
      password: process.env.AUTH_PASSWORD,
    })
  ) {
    return NextResponse.rewrite(
      `${request.nextUrl.protocol}//${request.nextUrl.host}/401`,
      {
        status: 401,
        headers: {
          "WWW-Authenticate": 'Basic realm="Secure Area"',
        },
      },
    );
  }

  return NextResponse.next();
}

phsantiago avatar Aug 02 '23 11:08 phsantiago

The middleware.ts/js of NextJS 13 must be placed in the root directory, and it will not work if placed under src.

feenn avatar Oct 26 '23 03:10 feenn