Next.js Discord

Discord Forum

Adding a second layer of middlware behind nextauth

Unanswered
Saltwater Crocodile posted this in #help-forum
Open in Discord
Saltwater CrocodileOP
How can I have 2 middleware layers liek is in the image?
basically if it passes the auth then it will go to the 2nd layer, but only if it matches the endpoint

46 Replies

You need to intercept first middleware, I had made a package that simplifies it:

https://www.npmjs.com/package/next-easy-middlewares

If you will run into any trouble with it, feel free to open issue on github and I will fix/add it soon
yeah, should be enough, and pass it to global middleware 😄
Saltwater CrocodileOP
alright ill try it in a bit and tell you how it works!
I think I will note that it would be nice to add a few examples to run, not only code in readme :lolsob:
sure, I'm waiting for feedback 😄
@Z4NR34L I think I will note that it would be nice to add a few examples to run, not only code in readme <:lolsob:753870958489632819>
Saltwater CrocodileOP
yeah i think you could add nextauth example :D
could you make issue on repo for that? 😄 If you have any other ideas, go for it as well. I'm prety open to improve this package
@Z4NR34L could you make issue on repo for that? 😄 If you have any other ideas, go for it as well. I'm prety open to improve this package
Saltwater CrocodileOP
yeah, just opened civ6 so im gonna play it for a bit and then if i dont forget ill for sure do it
haha, thanks 😄
remember to mark message with solution there if you consider this case as closed
Saltwater CrocodileOP
alright
@Z4NR34L remember to mark message with solution there if you consider this case as closed
Saltwater CrocodileOP
hi im trying to setup the middleware but im getting weird error, altough ive done(atleast i think) everything that is in the README
am i missing something?
As I see it’s type mismatch
Saltwater CrocodileOP
yep
You can temporarily fix that by passing it as never type:

export const middleware = createMiddleware(middlewares as never);
I will note that to fix it next update 😄
Saltwater CrocodileOP
Argument of type '{ '/app/admin/:path*': (request: NextRequest) => Promise<NextResponse<unknown>>; }' is not assignable to parameter of type 'MiddlewareConfig'.
  Property ''/app/admin/:path*'' is incompatible with index signature.
    Type '(request: NextRequest) => Promise<NextResponse<unknown>>' is not assignable to type 'MiddlewareFunction | MiddlewareFunction[]'.
      Type '(request: NextRequest) => Promise<NextResponse<unknown>>' is not assignable to type 'MiddlewareFunction'.
        Types of parameters 'request' and 'request' are incompatible.
          Property '[INTERNALS]' is missing in type 'import("/home/koblizkac/Coding/Webdev/myedu/node_modules/next-easy-middlewares/node_modules/next/dist/server/web/spec-extension/request").NextRequest' but required in type 'import("/home/koblizkac/Coding/Webdev/myedu/node_modules/next/dist/server/web/spec-extension/request").NextRequest'.ts(2345)
request.d.ts(7, 5): '[INTERNALS]' is declared here.

heres the error
Ok, so definitely gonna check that today as in my project it just works haha, can you share with me you tsconfig for analysis?
Saltwater CrocodileOP
sure
{
  "compilerOptions": {
    "target": "es5",
    "downlevelIteration": true,
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "bundler",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "plugins": [
      {
        "name": "next"
      }
    ],
    "paths": {
      "@/*": ["./src/*"]
    },
    "typeRoots": ["./types"],
    "suppressImplicitAnyIndexErrors": true,
    "ignoreDeprecations": "5.0"
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
  "exclude": ["node_modules"]
}
thanks a lot, here you can follow the progress on that 😄
I will get into that in 1-2h I think 🤔
Saltwater CrocodileOP
all good
I had just setup a clean next.js project, installed package and everything just works, so it looks like there is something in your tsconfig that causes this type mismatch, also don't export default from next-auth as it's already exporting middleware function
I will prepare an fast example with next-auth
Saltwater CrocodileOP
Alright thanks
I will share default tsconfig with you, so we will be able to compare them
Saltwater CrocodileOP
Alrigjt sure send the middleware here
{
  "compilerOptions": {
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "bundler",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "plugins": [
      {
        "name": "next"
      }
    ],
    "paths": {
      "@/*": ["./src/*"]
    }
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
  "exclude": ["node_modules"]
}
And default middleware just works with that tsconfig
import { createMiddleware } from 'next-easy-middlewares';
import { type NextRequest, NextResponse } from 'next/server';

const middlewares = {
  '/app/admin/:path*': async (request: NextRequest) => {
    return NextResponse.next();
  }
};

export const middleware = createMiddleware(middlewares);

export const config = {
  matcher: ['/((?!api/|_next/|_static|_vercel|[\\w-]+\\.\\w+).*)'],
};
Saltwater CrocodileOP
pokay i think i fixed it
but im not sure
show me 😄
I'm curious what was the issue
Saltwater CrocodileOP
i had to explicitly specify the type
oh wait
cant even load into the nextauth protected pages
okay but it seems to be my problem
hmm
it really seems to be my problem :D
your code works as expected
I see that I wanted it to be more future proof then probably needed, if you want just to run your own middleware after next-auth's there is ready solution for that in next-auth:

https://next-auth.js.org/configuration/nextjs#advanced-usage

If you will need any assistance, just let me know. I will also prepare docs in my package to covereage next-auth usage with it 🙂