Next.js Discord

Discord Forum

middleware __dirname is not defined

Answered
Gouty oak gall posted this in #help-forum
Open in Discord
Gouty oak gallOP
hey! currently building my first app router page and when deploying to vercel, am hitting a small block with the error:
ReferenceError: __dirname is not defined
    at (node_modules/next/dist/compiled/ua-parser-js/ua-parser.js:1:17315)
    at (node_modules/next/dist/compiled/ua-parser-js/ua-parser.js:1:17444)
    at (node_modules/next/dist/server/web/spec-extension/user-agent.js:27:59)
    at (node_modules/next/server.js:8:0)
    at (middleware.js:2:29)
    at (middleware:middleware.js:1:17)


here is what my middleware code looks like:

// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

const getValidSubdomain = (host?: string | null) => {
    let subdomain: string | null = null;
    if (!host && typeof window !== 'undefined') {
        // On client side, get the host from window
        host = window.location.host;
    }
    if (host && host.includes('.')) {
        const candidate = host.split('.')[0];
        if (candidate && !candidate.includes('localhost')) {
            // Valid candidate
            subdomain = candidate;
        }
    }
    return subdomain;
};

// RegExp for public files
const PUBLIC_FILE = /\.(.*)$/; // Files

export async function middleware(req: NextRequest) {
    // Clone the URL
    const url = req.nextUrl.clone();

    // Skip public files
    if (PUBLIC_FILE.test(url.pathname) || url.pathname.includes('_next')) return;

    const host = req.headers.get('host');
    const subdomain = getValidSubdomain(host);
    if (subdomain) {
        // Subdomain available, rewriting
        // console.log(`>>> Rewriting: ${url.pathname} to /${subdomain}${url.pathname}`);
        url.pathname = `/${subdomain}${url.pathname}`;
    } else {
        // console.log(">>> No subdomain available, skipping rewrite")
    }

    return NextResponse.rewrite(url);
}


any help is appreciated! :):sunglasses_1:
Answered by Gouty oak gall
@Ray so i deleted my project on vercel and then deployed it agian... and it fixed it ☠️
View full answer

15 Replies

@Gouty oak gall hey! currently building my first app router page and when deploying to vercel, am hitting a small block with the error: ReferenceError: __dirname is not defined at (node_modules/next/dist/compiled/ua-parser-js/ua-parser.js:1:17315) at (node_modules/next/dist/compiled/ua-parser-js/ua-parser.js:1:17444) at (node_modules/next/dist/server/web/spec-extension/user-agent.js:27:59) at (node_modules/next/server.js:8:0) at (middleware.js:2:29) at (middleware:middleware.js:1:17) here is what my middleware code looks like: // middleware.ts import { NextResponse } from 'next/server'; import type { NextRequest } from 'next/server'; const getValidSubdomain = (host?: string | null) => { let subdomain: string | null = null; if (!host && typeof window !== 'undefined') { // On client side, get the host from window host = window.location.host; } if (host && host.includes('.')) { const candidate = host.split('.')[0]; if (candidate && !candidate.includes('localhost')) { // Valid candidate subdomain = candidate; } } return subdomain; }; // RegExp for public files const PUBLIC_FILE = /\.(.*)$/; // Files export async function middleware(req: NextRequest) { // Clone the URL const url = req.nextUrl.clone(); // Skip public files if (PUBLIC_FILE.test(url.pathname) || url.pathname.includes('_next')) return; const host = req.headers.get('host'); const subdomain = getValidSubdomain(host); if (subdomain) { // Subdomain available, rewriting // console.log(`>>> Rewriting: ${url.pathname} to /${subdomain}${url.pathname}`); url.pathname = `/${subdomain}${url.pathname}`; } else { // console.log(">>> No subdomain available, skipping rewrite") } return NextResponse.rewrite(url); } any help is appreciated! :)<:sunglasses_1:767749456648339497>
is this code from chatgpt or something? :lolsob:
@Gouty oak gall hey! currently building my first app router page and when deploying to vercel, am hitting a small block with the error: ReferenceError: __dirname is not defined at (node_modules/next/dist/compiled/ua-parser-js/ua-parser.js:1:17315) at (node_modules/next/dist/compiled/ua-parser-js/ua-parser.js:1:17444) at (node_modules/next/dist/server/web/spec-extension/user-agent.js:27:59) at (node_modules/next/server.js:8:0) at (middleware.js:2:29) at (middleware:middleware.js:1:17) here is what my middleware code looks like: // middleware.ts import { NextResponse } from 'next/server'; import type { NextRequest } from 'next/server'; const getValidSubdomain = (host?: string | null) => { let subdomain: string | null = null; if (!host && typeof window !== 'undefined') { // On client side, get the host from window host = window.location.host; } if (host && host.includes('.')) { const candidate = host.split('.')[0]; if (candidate && !candidate.includes('localhost')) { // Valid candidate subdomain = candidate; } } return subdomain; }; // RegExp for public files const PUBLIC_FILE = /\.(.*)$/; // Files export async function middleware(req: NextRequest) { // Clone the URL const url = req.nextUrl.clone(); // Skip public files if (PUBLIC_FILE.test(url.pathname) || url.pathname.includes('_next')) return; const host = req.headers.get('host'); const subdomain = getValidSubdomain(host); if (subdomain) { // Subdomain available, rewriting // console.log(`>>> Rewriting: ${url.pathname} to /${subdomain}${url.pathname}`); url.pathname = `/${subdomain}${url.pathname}`; } else { // console.log(">>> No subdomain available, skipping rewrite") } return NextResponse.rewrite(url); } any help is appreciated! :)<:sunglasses_1:767749456648339497>
// middleware.ts
import { NextRequest, NextResponse } from "next/server";

const getValidSubdomain = (host?: string | null) => {
  let subdomain: string | null = null;

  if (host && host.includes(".")) {
    const candidate = host.split(".")[0];
    if (candidate && !candidate.includes("localhost")) {
      // Valid candidate
      subdomain = candidate;
    }
  }
  return subdomain;
};

export function middleware(req: NextRequest) {
  // Clone the URL
  const url = req.nextUrl.clone();

  const host = req.headers.get("host");
  const subdomain = getValidSubdomain(host);
  if (subdomain) {
    // Subdomain available, rewriting
    // console.log(`>>> Rewriting: ${url.pathname} to /${subdomain}${url.pathname}`);
    url.pathname = `/${subdomain}${url.pathname}`;
    return NextResponse.rewrite(url);
  }

  // console.log(">>> No subdomain available, skipping rewrite")
}

export const config = {
  matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - api (API routes)
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico (favicon file)
     */
    "/((?!api|_next/static|_next/image|favicon.ico).*)",
  ],
};

let's try this
@Ray is this code from chatgpt or something? <:lolsob:753870958489632819>
Gouty oak gallOP
lol. it's from a medium article
@Ray , still the same error, unfortunately:

ReferenceError: __dirname is not defined
    at (node_modules/next/dist/compiled/ua-parser-js/ua-parser.js:1:17315)
    at (node_modules/next/dist/compiled/ua-parser-js/ua-parser.js:1:17444)
    at (node_modules/next/dist/server/web/spec-extension/user-agent.js:27:59)
    at (node_modules/next/server.js:8:0)
    at (middleware.js:2:29)
    at (middleware:middleware.js:1:17)
thank you for the help tho :blobpray:
it weird, there is no __dirname
Gouty oak gallOP
i did some more testing around, and i think it's not even related to my code
i put in a example codeline for middleware from the nextjs docs, and it still gives the same error
there's gotta be an issue somewhere else. this sucks, it so hard to diagnose
const getValidSubdomain = (host?: string | null) => {
  let subdomain: string | null = null;

  if (host && host.includes(".")) {
    const candidate = host.split(".")[0];
    if (candidate && !candidate.includes("localhost")) {
      // Valid candidate
      subdomain = candidate;
    }
  }
  return subdomain;
};

export async function middleware(req: NextRequest) {
  // Clone the URL
  // const url = req.nextUrl.clone();

  const host = req.headers.get("host");
  const subdomain = getValidSubdomain(host);
  if (subdomain) {
    // Subdomain available, rewriting
    // console.log(`>>> Rewriting: ${url.pathname} to /${subdomain}${url.pathname}`);
    return NextResponse.rewrite(
      new URL(`/${subdomain}${req.nextUrl.pathname}`, req.nextUrl)
    );
  }

  // console.log(">>> No subdomain available, skipping rewrite")
}
try this
Gouty oak gallOP
@Ray so i deleted my project on vercel and then deployed it agian... and it fixed it ☠️
Answer
Gouty oak gallOP
rly appreciate ur help
@Gouty oak gall hey! currently building my first app router page and when deploying to vercel, am hitting a small block with the error: ReferenceError: __dirname is not defined at (node_modules/next/dist/compiled/ua-parser-js/ua-parser.js:1:17315) at (node_modules/next/dist/compiled/ua-parser-js/ua-parser.js:1:17444) at (node_modules/next/dist/server/web/spec-extension/user-agent.js:27:59) at (node_modules/next/server.js:8:0) at (middleware.js:2:29) at (middleware:middleware.js:1:17) here is what my middleware code looks like: // middleware.ts import { NextResponse } from 'next/server'; import type { NextRequest } from 'next/server'; const getValidSubdomain = (host?: string | null) => { let subdomain: string | null = null; if (!host && typeof window !== 'undefined') { // On client side, get the host from window host = window.location.host; } if (host && host.includes('.')) { const candidate = host.split('.')[0]; if (candidate && !candidate.includes('localhost')) { // Valid candidate subdomain = candidate; } } return subdomain; }; // RegExp for public files const PUBLIC_FILE = /\.(.*)$/; // Files export async function middleware(req: NextRequest) { // Clone the URL const url = req.nextUrl.clone(); // Skip public files if (PUBLIC_FILE.test(url.pathname) || url.pathname.includes('_next')) return; const host = req.headers.get('host'); const subdomain = getValidSubdomain(host); if (subdomain) { // Subdomain available, rewriting // console.log(`>>> Rewriting: ${url.pathname} to /${subdomain}${url.pathname}`); url.pathname = `/${subdomain}${url.pathname}`; } else { // console.log(">>> No subdomain available, skipping rewrite") } return NextResponse.rewrite(url); } any help is appreciated! :)<:sunglasses_1:767749456648339497>
Pont-Audemer Spaniel
in ESModules, we don't have global variables like __dirname and __filename.
if you want to get similar result in ESModules you can do the followings:
import path from "node:path";
import url from "node:url";

const currentFileUrl  = import.meta.url
const __filename = url.fileURLToPath(currentFileUrl)

const currentDirUrl = path.dirname(currentFileUrl)
const __dirname = url.fileURLToPath(currentDirUrl)