[ERR_HTTP_HEADERS_SENT]: Cannot append headers after they are sent to the client on middleware.js during authentication

I have a project where I do authentication checking on middleware.js file. It was doing fine locally and on development server, but when we deploy it to production it got:

[ERR_HTTP_HEADERS_SENT]: Cannot append headers after they are sent to the client
import { NextResponse } from 'next/server'
import { getBackendUrl } from './components/Constanta/Constanta'

// This function can be marked `async` if using `await` inside
export async function middleware(request) {
    const BE_URL = getBackendUrl('general')
    const token = request.cookies.get('token')
    if(token) {
        try {
            const response = await fetch(BE_URL+"check-auth/", {
                method: "GET",
                headers: {
                    'Authorization': `Bearer ${token.value}`,
                    "Content-Type": "application/json",
                },
            })
            if (!response.ok) {
                const resp = NextResponse.redirect(new URL('/login', request.url))
                resp.cookies.set("route", new URL(request.url).pathname);
                resp.cookies.set("token", null);
                resp.cookies.set("userID", null);
                resp.cookies.set("roleID", null);
                return resp
            } else {
                return NextResponse.next();
            }
        }
        catch (error) {
            console.log(error)
            const resp = NextResponse.redirect(new URL('/login', request.url));
            resp.cookies.set("route", new URL(request.url).pathname);
            return resp;    
        }
    } else {
        const resp = NextResponse.redirect(new URL('/login', request.url));
        resp.cookies.set("route", new URL(request.url).pathname);
        return resp;   
    }
}

 
// See "Matching Paths" below to learn more
export const config = {
    matcher: [
        '/',
        ...
    ],
}

Did I do something wrong? The production server should be mirroring the development server and I built it on Docker so I got confused here.