Next.js Discord

Discord Forum

Middleware seems to throw error when self hosted

Answered
Thrianta posted this in #help-forum
Open in Discord
ThriantaOP
This middleware works fine on Vercel, but I need to migrate to self hosted. This middleware seems to throw errors:
Answered by Thrianta
I was making the request from inside a docker container to the application's live url. Changing the url to be a localhost url fixed the error.

.....

// if theres no session token redirect early
  if (!sessionToken) return redirectToLogin()

  // check if this user is an admin or higher
  const res = await fetch(
    new URL("/api/auth/isElevatedSessionToken", "http://locahost:3000"), // replace "request.nextUrl.toString()" with "http://localhost:3000"
    {
      method: "POST",
      body: JSON.stringify({
        sessionToken,
      }),
    },
  )
  const { isElevated } = await res.json()

.....
View full answer

4 Replies

ThriantaOP
The error:

Error: fetch failed
    at context.fetch (/app/node_modules/.pnpm/next@14.2.3_@babel+core@7.24.5_react-dom@18.2.0_react@18.2.0__react@18.2.0/node_modules/next/dist/server/web/sandbox/context.js:292:38)
    at Object.eG [as handler] (/app/.next/server/src/middleware.js:13:28503)
    at /app/.next/server/src/middleware.js:13:24843
    at AsyncLocalStorage.run (node:async_hooks:346:14)
    at Object.wrap (/app/.next/server/src/middleware.js:13:22130)
    at /app/.next/server/src/middleware.js:13:24656
    at /app/.next/server/src/middleware.js:13:19434
    at o.with (/app/.next/server/src/middleware.js:13:40282)
    at l.with (/app/.next/server/src/middleware.js:13:34482)
    at l.startActiveSpan (/app/.next/server/src/middleware.js:13:49534) {
  cause: [Error: 804C03FF657F0000:error:0A00010B:SSL routines:ssl3_get_record:wrong version number:../deps/openssl/openssl/ssl/record/ssl3_record.c:354:
  ] {
    library: 'SSL routines',
    reason: 'wrong version number',
    code: 'ERR_SSL_WRONG_VERSION_NUMBER'
  }
}
{... more in next message ...}
Continued:

Error [ERR_HTTP_HEADERS_SENT]: Cannot append headers after they are sent to the client
    at ServerResponse.appendHeader (node:_http_outgoing:715:11)
    at /app/node_modules/.pnpm/next@14.2.3_@babel+core@7.24.5_react-dom@18.2.0_react@18.2.0__react@18.2.0/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:16:23936
    at _Headers.forEach (node:internal/deps/undici/undici:4354:26)
    at w (/app/node_modules/.pnpm/next@14.2.3_@babel+core@7.24.5_react-dom@18.2.0_react@18.2.0__react@18.2.0/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:16:23918)
    at R (/app/node_modules/.pnpm/next@14.2.3_@babel+core@7.24.5_react-dom@18.2.0_react@18.2.0__react@18.2.0/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:12:83072)
    at nq (/app/node_modules/.pnpm/next@14.2.3_@babel+core@7.24.5_react-dom@18.2.0_react@18.2.0__react@18.2.0/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:12:69672)
    at n1 (/app/node_modules/.pnpm/next@14.2.3_@babel+core@7.24.5_react-dom@18.2.0_react@18.2.0__react@18.2.0/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:12:81755)
    at AsyncLocalStorage.run (node:async_hooks:346:14)
    at Timeout._onTimeout (/app/node_modules/.pnpm/next@14.2.3_@babel+core@7.24.5_react-dom@18.2.0_react@18.2.0__react@18.2.0/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:12:87775)
    at listOnTimeout (node:internal/timers:581:17) {
  code: 'ERR_HTTP_HEADERS_SENT',
  digest: '1408950558'
}
The middleware in question:

import { cookies } from "next/headers"
import { NextRequest, NextResponse } from "next/server"

/**
 * This is a middleware that only protects admin routes
 */
export default async function middleware(req: NextRequest) {
  /**
   * Helper function to redirect
   * @returns NextResponse.redirect
   */
  function redirectToLogin() {
    return NextResponse.redirect(
      new URL(
        `/api/auth/signin?callbackUrl=${req.nextUrl.pathname}`,
        req.nextUrl.toString(),
      ),
    )
  }

  // get all cookies
  const _cookies = cookies().toString()

  // try and get session token
  const sessionToken = _cookies.match(/next-auth\.session-token=([^;]+)/)?.at(1)

  // if theres no session token redirect early
  if (!sessionToken) return redirectToLogin()

  // check if this user is an admin or higher
  const res = await fetch(
    new URL("/api/auth/isElevatedSessionToken", req.nextUrl.toString()),
    {
      method: "POST",
      body: JSON.stringify({
        sessionToken,
      }),
    },
  )
  const { isElevated } = await res.json()

  // if is not elevated, redirect to login
  if (!isElevated)
    return NextResponse.redirect(new URL("/", req.nextUrl.toString()))

  // finally continue
  return
}

export const config = { matcher: ["/admin/:path*"] }
ThriantaOP
I was making the request from inside a docker container to the application's live url. Changing the url to be a localhost url fixed the error.

.....

// if theres no session token redirect early
  if (!sessionToken) return redirectToLogin()

  // check if this user is an admin or higher
  const res = await fetch(
    new URL("/api/auth/isElevatedSessionToken", "http://locahost:3000"), // replace "request.nextUrl.toString()" with "http://localhost:3000"
    {
      method: "POST",
      body: JSON.stringify({
        sessionToken,
      }),
    },
  )
  const { isElevated } = await res.json()

.....
Answer