Next.js Discord

Discord Forum

Help for middleware

Answered
Verin posted this in #help-forum
Open in Discord
how to redirect the route to the "auth/signin" if the value of the session.user.role is not "ADMIN" with middleware as middleware.ts not js?
Any solution?
Answered by Ray
// add this to the option
callbacks: {
    jwt({ token, session }) {
      if (session.user.role) {
        token.userRole = session.user.role;
      }
      return token;
    },
  },
View full answer

72 Replies

you get the session in middleware
and write conditional
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { getSession } from "next-auth/react"

export async function middleware(request: NextRequest) {
    const session = await getSession({ req: request });

    if(session){
        return NextResponse.redirect('/empresa/mis-empresas')
    }
}
smthing like this
you do conditional routing
I've tried this but get error.
what error?
hmm, can you put request as any for now, and remove that export {default} live above
let me try now.
export {default} is harmful?
only one middleware will work
both won't
That is for redirecting to signin page if not logged.
Then do I have to make that logic in the middleware?
yes
compiling now
no wait, you can add your own logic
use withAuth
exactly which part?
@Verin exactly which part?
try this
// middleware.ts
import { withAuth } from "next-auth/middleware";
import { NextResponse } from "next/server";

export default withAuth((req) => {
  if (req.nextauth) {
    return NextResponse.redirect(new URL("/empresa/mis-empresas", req.url));
  }
});
@averydelusionalperson you get the session in middleware
@Ray use `withAuth`
I have to check the session because session have the user role like "ADMIN" and "USER".
so that I can redirect if not admin try to access to the admin route.
I've setup correctly.
do you see it in req.nextauth.token.role then
Is the token same with the session?
The below is the [...nextauth]
I am not using the jwt.
@Verin Is the token same with the session?
it should
This is the token I've got.
@Verin I am not using the jwt.
how did you set the role to session?
let me show you that code.
@Verin Click to see attachment
are you using mongoose?
yes
I think you will need to use next-auth v5
next-auth
@Ray I think you will need to use `next-auth` v5
so if I use v5, how can I manage this?
@Verin so if I use v5, how can I manage this?
npm i next-auth@beta
I am installing it.
If I use v5, can I get the role at the token?
you can get the role in v4 too, but mongoose doesn't work in middleware
next-auth v5 provide a way to make it work
config the next-auth with this example
hello bro.
auth is not problem for me now.
but you need to check the session inside middleware right?
yes.
and you are using database session with mongodb right?
no?
@Verin Click to see attachment
where is the User.findOne() coming from?
@Ray no?
that is the third part and I am not using it for nextjs authentication.
@Verin I am not using the jwt.
and you said you are not using jwt strategy
yes
so you are using database session strategy
what does the nextjs use the database session strategy?
I know, that is my bad presentation.
Please consider this.
I wanna check this role in the middleware.
@Verin I wanna check this role in the middleware.
only work if you use jwt strategy in v4
// add this to the option
callbacks: {
    jwt({ token, session }) {
      if (session.user.role) {
        token.userRole = session.user.role;
      }
      return token;
    },
  },
Answer
//middleware.ts
import { withAuth } from "next-auth/middleware";
import { NextResponse } from "next/server";

export default withAuth((req) => {
  if (req.nextauth.token?.userRole) {
    return NextResponse.redirect(new URL("/empresa/mis-empresas", req.url));
  }
});
if you are using typescript
declare module "next-auth/jwt" {
    /** Returned by the `jwt` callback and `getToken`, when using JWT sessions */
    interface JWT {
      /** OpenID ID Token */
      userRole?: string
    }
  }
let me try
so Is there any way to get the session in the middleware?