vercel / next.js

The React Framework
https://nextjs.org
MIT License
126.47k stars 26.91k forks source link

ReferenceError: __dirname is not defined in Next.js app despite not using ua-parser-js #53968

Closed j4nos closed 1 year ago

j4nos commented 1 year ago

Verify canary release

Provide environment information

I'm encountering an unexpected error in my Next.js app that's puzzling me. Despite not using the ua-parser-js package in my codebase, I'm getting the error message ReferenceError: __dirname is not defined. I've thoroughly reviewed my code and dependencies, but I can't seem to pinpoint the source of the issue.

ReferenceError: __dirname is not defined
    at (node_modules/next/dist/compiled/ua-parser-js/ua-parser.js:10:16756)
    at (node_modules/next/dist/compiled/ua-parser-js/ua-parser.js:10:16885)
    at (node_modules/next/dist/server/web/spec-extension/user-agent.js:8:41)
    at (node_modules/next/server.js:6:0)
    at (middleware.js:1:29)
    at (middleware:middleware.js:1:17)

Here are some key details about my project setup:

Regenerated the yarn.lock file.

Despite these efforts, the error persists. I suspect it might be related to some deeper configuration or a combination of factors.

Has anyone encountered a similar issue where a ReferenceError: __dirname is not defined error occurs even when not directly using the ua-parser-js package? Are there any specific steps I should take to troubleshoot this issue further? Any insights or suggestions would be greatly appreciated.

Code Samples:

Here's the code for my middleware.ts file, where the error seems to originate:

import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

const allowedOrigins = [
    'http://localhost:8888', // Add your frontend URLs here
    'https://borespiac.hu',
    'https://tikex-mongo-prod.vercel.app',
    'https://tikex-mongo-prod-git-main-j4nos.vercel.app',
    // Add more URLs as needed
]

export function middleware(request: NextRequest) {
    const origin = request.headers.get('Origin')

    if (origin && allowedOrigins.includes(origin)) {
        const responseHeaders = new Headers()
        responseHeaders.append('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        responseHeaders.append(
            'Access-Control-Allow-Headers',
            'Content-Type, Authorization'
        )
        responseHeaders.append('Access-Control-Allow-Credentials', 'true')
        responseHeaders.append('Access-Control-Allow-Origin', origin)

        if (request.method === 'OPTIONS') {
            return new Response(null, {
                status: 200,
                headers: responseHeaders,
            })
        } else {
            // Let the original response continue through the middleware chain
            const response = NextResponse.next({})

            // Set the desired CORS headers for the response
            response.headers.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
            response.headers.set(
                'Access-Control-Allow-Headers',
                'Content-Type, Authorization'
            )
            response.headers.set('Access-Control-Allow-Credentials', 'true')
            response.headers.set('Access-Control-Allow-Origin', origin)

            return response
        }
    }

    return NextResponse.next({})
}

next.config.js

module.exports = {
    images: {
        domains: [
            'ticket-t01.s3.eu-central-1.amazonaws.com',
            't44-photo.s3.eu-central-1.amazonaws.com',
            't44-post-cover.s3.eu-central-1.amazonaws.com',
            'media.istockphoto.com',
            'themes.framework-y.com',
            'themekit.dev',
        ],
        deviceSizes: [320, 375, 450, 540, 640, 750, 828, 1080, 1200, 1920],
    },
    reactStrictMode: true,
    poweredByHeader: false,
    async headers() {
        return []
    },
}

Which area(s) of Next.js are affected? (leave empty if unsure)

Middleware / Edge (API routes, runtime)

Link to the code that reproduces this issue or a replay of the bug

https://tikex-mongo-prod-git-main-j4nos.vercel.app

To Reproduce

App is not opening, build was successful.

Describe the Bug

Got this error:

ReferenceError: __dirname is not defined
    at (node_modules/next/dist/compiled/ua-parser-js/ua-parser.js:10:16756)
    at (node_modules/next/dist/compiled/ua-parser-js/ua-parser.js:10:16885)
    at (node_modules/next/dist/server/web/spec-extension/user-agent.js:8:41)
    at (node_modules/next/server.js:6:0)
    at (middleware.js:1:29)
    at (middleware:middleware.js:1:17)

Expected Behavior

Landing page appears.

Which browser are you using? (if relevant)

Chrome

How are you deploying your application? (if relevant)

No response

balazsorban44 commented 1 year ago

Could you please link to the actual repository?

github-actions[bot] commented 1 year ago

We cannot recreate the issue with the provided information. Please add a reproduction in order for us to be able to investigate.

Why was this issue marked with the please add a complete reproduction label?

To be able to investigate, we need access to a reproduction to identify what triggered the issue. We prefer a link to a public GitHub repository (template for App Router, template for Pages Router), but you can also use these templates: CodeSandbox: App Router or CodeSandbox: Pages Router.

To make sure the issue is resolved as quickly as possible, please make sure that the reproduction is as minimal as possible. This means that you should remove unnecessary code, files, and dependencies that do not contribute to the issue. Ensure your reproduction does not depend on secrets, 3rd party registries, private dependencies, or any other data that cannot be made public. Avoid a reproduction including a whole monorepo (unless relevant to the issue). The easier it is to reproduce the issue, the quicker we can help.

Please test your reproduction against the latest version of Next.js (next@canary) to make sure your issue has not already been fixed.

If you cannot create a clean reproduction, another way you can help the maintainers' job is to pinpoint the canary version of next that introduced the issue. Check out our releases, and try to find the first canary release that introduced the issue. This will help us narrow down the scope of the issue, and possibly point to the PR/code change that introduced it. You can install a specific version of next by running npm install next@<version>.

I added a link, why was it still marked?

Ensure the link is pointing to a codebase that is accessible (e.g. not a private repository). "example.com", "n/a", "will add later", etc. are not acceptable links -- we need to see a public codebase. See the above section for accepted links.

What happens if I don't provide a sufficient minimal reproduction?

Issues with the please add a complete reproduction label that receives no meaningful activity (e.g. new comments with a reproduction link) are automatically closed and locked after 30 days.

If your issue has not been resolved in that time and it has been closed/locked, please open a new issue with the required reproduction.

I did not open this issue, but it is relevant to me, what can I do to help?

Anyone experiencing the same issue is welcome to provide a minimal reproduction following the above steps. Furthermore, you can upvote the issue using the :+1: reaction on the topmost comment (please do not comment "I have the same issue" without reproduction steps). Then, we can sort issues by votes to prioritize.

I think my reproduction is good enough, why aren't you looking into it quicker?

We look into every Next.js issue and constantly monitor open issues for new comments.

However, sometimes we might miss one or two due to the popularity/high traffic of the repository. We apologize, and kindly ask you to refrain from tagging core maintainers, as that will usually not result in increased priority.

Upvoting issues to show your interest will help us prioritize and address them as quickly as possible. That said, every issue is important to us, and if an issue gets closed by accident, we encourage you to open a new one linking to the old issue and we will look into it.

Useful Resources

appienvanveen commented 1 year ago

Got the same issue deploying an angular project with middleware.ts

ReferenceError: __dirname is not defined
    at (node_modules/next/dist/compiled/ua-parser-js/ua-parser.js:10:16756)
    at (node_modules/next/dist/compiled/ua-parser-js/ua-parser.js:10:16885)
    at (node_modules/next/dist/server/web/spec-extension/user-agent.js:8:41)
    at (node_modules/next/server.js:6:0)
    at (middleware.js:1:29)
    at (middleware:middleware.js:1:17)

next 13.4.2. angular 14

appienvanveen commented 1 year ago

updating to latest next js package i get

[08:05:59.527] Running build in Washington, D.C., USA (East) – iad1 (Hive)
[08:05:59.628] Cloning github.com/appienvanveen/angular-boilerplate (Branch: main, Commit: f23f5e3)
[08:06:00.111] Cloning completed: 481.941ms
[08:06:04.720] Restored build cache
[08:06:04.790] Running "vercel build"
[08:06:05.238] Vercel CLI 32.3.1
[08:06:06.256] Installing dependencies...
[08:06:13.826] 
[08:06:13.827] added 15 packages, and removed 1 package in 7s
[08:06:13.827] 
[08:06:13.827] 86 packages are looking for funding
[08:06:13.827]   run `npm fund` for details
[08:06:13.852] Detected `package-lock.json` generated by npm 7+
[08:06:13.852] Running "npm run build"
[08:06:14.285] 
[08:06:14.285] > build
[08:06:14.285] > ng build
[08:06:14.285] 
[08:06:16.884] - Generating browser application bundles (phase: setup)...
[08:06:33.364] ✔ Browser application bundle generation complete.
[08:06:33.367] ✔ Browser application bundle generation complete.
[08:06:33.368] - Copying assets...
[08:06:33.374] ✔ Copying assets complete.
[08:06:33.374] - Generating index html...
[08:06:33.394] ✔ Index html generation complete.
[08:06:33.398] 
[08:06:33.399] Initial Chunk Files           | Names         |  Raw Size | Estimated Transfer Size
[08:06:33.399] main.81d1c3c67616ff5f.js      | main          | 195.51 kB |                53.47 kB
[08:06:33.399] polyfills.125b2b1f5b5bda4b.js | polyfills     |  33.08 kB |                10.67 kB
[08:06:33.399] runtime.0ecabf6f212b1ce5.js   | runtime       | 902 bytes |               518 bytes
[08:06:33.399] styles.ef46db3751d8e999.css   | styles        |   0 bytes |                       -
[08:06:33.399] 
[08:06:33.399] | Initial Total | 229.48 kB |                64.65 kB
[08:06:33.399] 
[08:06:33.399] Build at: 2023-09-26T06:06:33.396Z - Hash: 20c33626ccfdc316 - Time: 16343ms
[08:06:33.945] Using TypeScript 4.8.4 (local user-provided)
[08:06:37.247] Build Completed in /vercel/output [31s]
[08:06:37.375] Deploying outputs...
[08:06:38.970] Error: The Edge Function "middleware" is referencing unsupported modules:
[08:06:38.970]  - next: stream, fs, url, path
appienvanveen commented 1 year ago

It's easy to reproduce.

github-actions[bot] commented 11 months ago

This closed issue has been automatically locked because it had no new activity for 2 weeks. If you are running into a similar issue, please create a new issue with the steps to reproduce. Thank you.