Theo's Typesafe CultTTC
Theo's Typesafe Cult2y ago
6 replies
Nizar

How to implement the correct middleware in NextJS TRPC

I'm confused why this middleware doesn't work on nextjs version 13 which uses the pages directory.

/middleware.ts
import routesDashboard from "@/dashboard/routes"
import withAuthorization from "@/middlewares/withAuthorization"
import { type NextMiddleware, type NextRequest, NextResponse } from "next/server"

const dashboardMiddleware: NextMiddleware = (_: NextRequest) => {
  const res = NextResponse.next()
  return res
}

export default withAuthorization(dashboardMiddleware, routesDashboard)


/src/middlewares/withAuthorization
// ...import

export default function withAuthorization(
  middleware: NextMiddleware,
  requireAuth: RoutesDashboard[] = []
) {
  return async (req: NextRequest, next: NextFetchEvent) => {
    const pathname = req.nextUrl.pathname
    const token = await getToken({
      req,
      secret: process.env.NEXTAUTH_SECRET,
    })

    if (pathname.startsWith("/auth")) {
      if (token) {
        const url = new URL("/dashboard", req.url)
        return NextResponse.rewrite(url)
      }
    }

    if (pathname.startsWith("/dashboard")) {
      const path = requireAuth.find(
        (path) =>
          pathname.startsWith(`${path.layout}${path.path}`)
      )

      if (path) {
        if (!token) {
          const url = new URL("/auth/signin", req.url)
          url.searchParams.set("callbackUrl ", encodeURI(req.url))
          return NextResponse.redirect(url)
        }

        if (path.children) {
          //...logic
        } else {
          if (
            path.rules &&
            path.rules.includes(token.role)
          ) {
            const url = new URL("/403", req.url)
            return NextResponse.rewrite(url)
          }
        }
      }
    }

    return middleware(req, next)
  }
}
Solution
FIX

Sorry it was an error in the folder placement
Was this page helpful?