Next.js Discord

Discord Forum

useReducer middleware authentication error

Unanswered
Dwarf Crocodile posted this in #help-forum
Open in Discord
Dwarf CrocodileOP
I am trying to make a sign in remember me authentication middleware.

I am using firebase for my user authentication, and so I have a hook named "useAuthState" that checks if a user is logged in.

I get the error "Cannot read properties of null (reading 'useReducer')"
From what I understand, it is caused due to the fact that a middleware is a server side running file, while the hook can only be used on the client side.

Is there any way to fix this? Or maybe if someone knows a good way to create a firebase user authentication middleware?

Here's my code for further understanding of the issue:
export function middleware(request: Request) {
    
    const [user, loading] = useAuthState(auth)


        if(user) {
            return NextResponse.redirect(new URL('/home',request.url))

        }
        else
            console.log("not logged in")
}

6 Replies

Kurilian Bobtail
middleware is on server...expecting not to handle user state as such....You should be able to check in cookies for access token... When you login that authorsation string you receive needs to be stored somewhere...
Dwarf CrocodileOP
So basically, because the middleware is on the serverside, I can't verify the sign in of the user because I am supposed to do it on the client side, to check if the user has login information stored in cookies or localstorage, right?
you can only call hooks on components, hooks can run both in the server and the client. the issue with the code is that its trying to be called from a middleware which is a completely different thing. if you want to handle user authentication within the middleware you need to do that by reading the cookies. keep in mind that the middleware should run as fast as possible so it is not advised to add network requests that could take too much time
Kurilian Bobtail
What I did in a learning project was creating function for /api pages to validate the token.

such as validatePermission(req,res,role?:admin|user, callback:()=>{}) and use it in authorised endpoints....

Not suggesting performing db calls in middleware file because it triggers multiple times.

Also...you will have in req.cookies or sth like that the cookies set...so you can definitely check in server side
Golden-winged Warbler
middleware should run as fast as possible so it is not advised to add network requests that could take too much time
@Rafael Almeida when deploying on vercel, is the middleware run separately and invoked by a network call? (hence why we cannot use the node runtime ever in that file)
Golden-winged Warbler
a follow on question, when you self-host a nextjs app, and everything runs together, is the middleware part of the same process? (resulting in a function call rather than a network request?)