Skip to content

[BUG] Windows build fails with Middleware and throws error without Middleware using better-auth #494

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
aleksa-codes opened this issue Mar 24, 2025 · 6 comments
Labels
bug Something isn't working

Comments

@aleksa-codes
Copy link

Describe the bug

I am trying to build and deploy a Next.js app using Drizzle, Cloudflare D1, better-auth and OpenNext. After digging deep to get this to work on the local development environment when running yarn dev (next dev) works as expected, I can sign up and sign in and the middleware redirects.

  1. The issue arises when trying to run yarn preview (opennextjs-cloudflare && wrangler dev --port 3000) with the middleware, this is what I get, both on Windows and Windows using WSL:
Bundling middleware function...
X [ERROR] Could not resolve "D:Projects\next-better-auth-drizzle-d1.nextserveredge-runtime-webpack.js"

    node_modules/@opennextjs/aws/dist/core/edgeFunctionHandler.js:8:8:
      8 │ require("D:\Projects\next-better-auth-drizzle-d1\.next\server\edge-runtime-webpack.js");
        ╵         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  You can mark the path "D:Projects\next-better-auth-drizzle-d1.nextserveredge-runtime-webpack.js"
  as external to exclude it from the bundle, which will remove this error. You can also surround
  this "require" call with a try/catch block to handle this failure at run-time instead of
  bundle-time.

X [ERROR] Could not resolve "D:Projects\next-better-auth-drizzle-d1.nextserversrcmiddleware.js"

    node_modules/@opennextjs/aws/dist/core/edgeFunctionHandler.js:9:8:
      9 │ require("D:\Projects\next-better-auth-drizzle-d1\.next\server\src\middleware.js");
        ╵         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  You can mark the path "D:Projects\next-better-auth-drizzle-d1.nextserversrcmiddleware.js" as
  external to exclude it from the bundle, which will remove this error. You can also surround this
  "require" call with a try/catch block to handle this failure at run-time instead of bundle-time.

D:\Projects\next-better-auth-drizzle-d1\node_modules\@opennextjs\aws\node_modules\esbuild\lib\main.js:1649
  let error = new Error(text);
  1. Removing the middleware makes the preview build successful, but when trying to sign up or sign in new error occurs that I found mentioned here already [BUG] Error: Invariant: renderHTML should not be called in minimal mode #333 (comment):
✘ [ERROR] ⨯ TypeError: Cannot read properties of undefined (reading 'definition')

The main files that got me to this point, since I already faced some issues before like this.client.prepare is not a function mentioned on better-auth Discord server, are:

  1. based on https://github.com/Dhravya/cloudflare-saas-stack/blob/main/drizzle.config.ts:
    drizzle.config.ts
import path from 'node:path';
import * as fs from 'node:fs';
import { defineConfig } from 'drizzle-kit';

function getLocalD1DB() {
  try {
    const basePath = path.resolve('.wrangler');
    const dbFile = fs.readdirSync(basePath, { encoding: 'utf-8', recursive: true }).find((f) => f.endsWith('.sqlite'));

    if (!dbFile) {
      throw new Error('.sqlite file not found');
    }

    const url = path.resolve(basePath, dbFile);
    return url;
  } catch (e) {
    console.error(`Error ${e}`);
  }
}

export default defineConfig({
  dialect: 'sqlite',
  schema: './src/db/schema/auth.ts',
  out: './src/db/migrations',
  casing: 'snake_case',
  ...(process.env.NODE_ENV === 'production'
    ? {
        driver: 'd1-http',
        dbCredentials: {
          accountId: process.env.CLOUDFLARE_ACCOUNT_ID,
          databaseId: process.env.CLOUDFLARE_D1_DATABASE_ID,
          token: process.env.CLOUDFLARE_D1_API_TOKEN,
        },
      }
    : {
        dbCredentials: {
          url: getLocalD1DB(),
        },
      }),
});
  1. based on https://github.com/Bekacru/better-auth-nextjs-cf-d1-example/blob/main/src/lib/db.ts:
    /src/db/index.ts
import { drizzle } from 'drizzle-orm/d1';
import { getCloudflareContext } from '@opennextjs/cloudflare';

async function initDbDev() {
  const { env } = await getCloudflareContext({ async: true });
  return drizzle(env.DB, {
    logger: true,
    casing: 'snake_case',
  });
}

function initDbProd() {
  return drizzle(process.env.DB, {
    logger: true,
    casing: 'snake_case',
  });
}

export const db = process.env.NODE_ENV === 'production' ? initDbProd() : await initDbDev();

Compared to #483 (comment) that solved other similar issue I am not specifying node runtime in the middleware and same as the PR mentioned in that comment https://github.com/serban-mihai/opennext-better-auth/pull/1/files I am using: import { getSessionCookie } from "better-auth/cookies"; in the middleware.

Everything else is based on the working project I already have that is using Supabase and deployed to Vercel, with of course things like schema and everything else adapted to use D1 (SQLite) instead of Postgres.

Steps to reproduce

Minimum Reproduction

  1. git clone [email protected]:aleksa-codes/next-better-auth-drizzle-d1.git
  2. yarn install or npm install
  3. Since there are already migration files in src/db/migrations run: yarn db:migrate:local or npm run db:migrate:local
  4. Set .dev.vars and .env.local based on the examples (RESEND_API_KEY is not needed)
  5. Run yarn dev or npm run dev and try to register and after sign in, it should work as on my machine
  6. Run yarn preview or npm run preview script.
  7. Error related to middleware should occur during the build: X [ERROR] Could not resolve "D:Projects\next-better-auth-drizzle-d1.nextserveredge-runtime-webpack.js" etc.
  8. Delete the middleware and run yarn preview or npm run preview again.
  9. This time build should be successful but if you try to register or login you should see [BUG] Error: Invariant: renderHTML should not be called in minimal mode #333 (comment): ✘ [ERROR] ⨯ TypeError: Cannot read properties of undefined (reading 'definition')

Expected behavior

The app should build and the middleware should redirect you to /signin if you try to access /protected whenever an auth session cookie is missing from the client storage.

With and without the middleware the user should be able to register or login, similar to when the app is being ran using next dev.

The local dev environment works fine using next dev, the preview using opennextjs-cloudflare && wrangler dev --port 3000 is not. I have not yet tested production as I cannot get the local preview to work.

@opennextjs/cloudflare version

0.5.12

Wrangler version

4.4.0

next info output

Operating System:
  Platform: win32
  Arch: x64
  Version: Windows 11 Pro
  Available memory (MB): 16310
  Available CPU cores: 12
Binaries:
  Node: 22.14.0
  npm: 10.9.2
  Yarn: 1.22.22
  pnpm: N/A
Relevant Packages:
  next: 15.2.3 // Latest available version is detected (15.2.3).
  eslint-config-next: 15.2.3
  react: 19.0.0
  react-dom: 19.0.0
  typescript: 5.8.2
Next.js Config:
  output: N/A

Additional context

The app uses Resend for email auth verification, but those parts of the code in src/lib/auth.ts have been commented out for easier testing, so the RESEND_API_KEY is not required. I left the comment in dev.vars.example and env.local.example on how to generate if you need BETTER_AUTH_SECRET.

One thing that I am aware of and whoever reads this should keep in mind that I am as I already mentioned on the Discord server fairly new to using D1 and OpenNext for deploying on the Cloudflare Workers, I have used Cloudflare pages before for Next.js and deployed some Astro sites. I am saying this because for example I cannot understand the difference between .dev.vars and .env yet and when is which one used, for example in my src/db/index.ts, and if for example Preview is still considered development environment or not in this case, and things of that nature.

Hope I wrote the issue good enough, gave my best shot to describe things.

@aleksa-codes aleksa-codes added bug Something isn't working triage labels Mar 24, 2025
@vicb vicb changed the title [BUG] Preview build fails with Middleware and throws error without Middleware using better-auth [BUG] Windows build fails with Middleware and throws error without Middleware using better-auth Mar 24, 2025
@vicb vicb removed the triage label Mar 24, 2025
@aleksa-codes
Copy link
Author

aleksa-codes commented Mar 27, 2025

After upgrading to "@opennextjs/cloudflare": "^0.6.2" and package.json scripts to:

    "preview": "opennextjs-cloudflare build && opennextjs-cloudflare preview",
    "deploy": "opennextjs-cloudflare build && opennextjs-cloudflare deploy",
    "cf-typegen": "wrangler types --env-interface CloudflareEnv cloudflare-env.d.ts"

Preview script (on Windows/WSL) with middleware still throws the same error, but without middleware still builds and now opennextjs-cloudflare preview throws:

error Couldn't find the binary wrangler
ERROR Wrangler command failed
error Command failed with exit code 1.

Update:
Found a Linux machine and looks like the problem is indeed only on Windows, but when I try to sign up or sign in, I am getting this now:

✘ [ERROR] ⨯ TypeError: Cannot read properties of undefined (reading 'prepare')

@AimanHakeem
Copy link

did anyone got solution to this? i'm having same issue as well.

Image

@rvanhorn
Copy link

rvanhorn commented Apr 3, 2025

Had a similar issue, only way I was able to resolve it was to setup WSL and dev from there.

@aleksa-codes
Copy link
Author

did anyone got solution to this? i'm having same issue as well.

Image

Hi @AimanHakeem, in my case working on a Linux machine solved this issue, as I was not able to get it to work via WSL on Windows. Should also work on Mac since it is Unix-based.

Also to leave an update I managed to get the local preview working and solved the:
✘ [ERROR] ⨯ TypeError: Cannot read properties of undefined (reading 'prepare')

the problem was in my /src/db/index.ts, it looks like this now:

import { drizzle } from 'drizzle-orm/d1';
import { getCloudflareContext } from '@opennextjs/cloudflare';

async function initDb() {
  const { env } = await getCloudflareContext({ async: true });

  if (!env.DB) {
    throw new Error('DB is not defined in the environment variables');
  }

  return drizzle(env.DB, {
    logger: true,
    casing: 'snake_case',
  });
}

export const db = await initDb();

https://github.com/aleksa-codes/next-better-auth-drizzle-d1/blob/main/src/db/index.ts

@aleksa-codes
Copy link
Author

aleksa-codes commented Apr 11, 2025

I solved my errors and maintainers seem to be aware of Windows issues, so I think the issue can be closed. Thanks 🙂

As a long time Cloudflare customer I can say that the experience here and on the Discord server has been pretty bad to say the least. The communication has been very strict and even passive aggressive at some point, while I was nothing but polite and professional. Not sure if it is related to my lack of experience, AI avatar or just frustration coming from working overtime. I will stick to "just reading the docs 🙂".

@humblepoc
Copy link

Apologies for heated discussion on bugs.
It happened out of frustration because of the issue.

Anyways thanks for the support @vicb & maintainers
Again, sincere apologies

#568

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

5 participants