sentry-javascript icon indicating copy to clipboard operation
sentry-javascript copied to clipboard

[sentry/cloudflare] Sentry import breaks Env type

Open shmuli9 opened this issue 8 months ago • 17 comments

Is there an existing issue for this?

How do you use Sentry?

Sentry Saas (sentry.io)

Which SDK are you using?

@sentry/cloudflare

SDK Version

9.13.0

Framework Version

React Router 7.5.1, Vite 6.3.0, Wrangler 4.12.0

Link to Sentry event

No response

Reproduction Example/SDK Setup

// worker file: ./workers/app.ts

import { getLoadContext } from "load-context";
import { createRequestHandler } from "react-router";
import * as Sentry from "@sentry/cloudflare"; // <-- this line breaks the Env types

const requestHandler = createRequestHandler(
  () => import("virtual:react-router/server-build"),
  import.meta.env.MODE
);

export default {
  async fetch(request, env, ctx) {
    const url = new URL(request.url);
    if (url.pathname.startsWith("/r2")) {
      const key = url.pathname.replace(/^\/r2\//, "");
      const object = await env.BUCKET.get(key);
      if (!object) {
        return new Response("Not found", { status: 404 });
      }
      return new Response(object.body, {
        headers: { "Content-Type": "image/jpeg" },
      });
    }

    const loadContext = getLoadContext({
      request,
      context: { cloudflare: { env, ctx } },
    });
    return requestHandler(request, loadContext);
  },
} satisfies ExportedHandler<Env>;

Steps to Reproduce

  1. installed @sentry/cloudflare v9.13.0
  2. added the import to workers/app.ts import * as Sentry from "@sentry/cloudflare"; // <-- this line breaks the Env types
  3. my env types break in when i typecheck
  4. commenting out the import fixes the type errors // import * as Sentry from "@sentry/cloudflare";

Expected Result

Types should not be corrupted by import Sentry

Actual Result

Broken:

Image

Image

Working (when import is commented out):

Image

shmuli9 avatar Apr 21 '25 12:04 shmuli9

I cannot reproduce this in the exact way you're describing. I am getting a type error on env.BUCKET however that is unrelated to Sentry and simply happens when I run npm run cf-typegen or wrangler types.

Commenting and uncommenting the import doesn't change anything for me. Would you mind sharing a reproduction example we can pull?

lforst avatar Apr 22 '25 11:04 lforst

I'm also experiencing this behavior. It exists when using the newest wrangler setup. In newer setups the root typescript does not include @cloudflare/workers-types but instead includes ./worker-configuration.d.ts. This file is generated with wrangler types.

Then my tsconfig has something like this in it:

         "compilerOptions": {
		"lib": ["DOM", "DOM.Iterable", "ES2023"],
		"types": ["./worker-configuration.d.ts", "vite/client"],
		"baseUrl": ".",
		"rootDirs": [".", "./.react-router/types"],
	}

I don't even have @cloudflare/workers-types installed at all.

So when I add import * as Sentry from @sentry/cloudflaresuddenly theEnvdefinition in my whole app is empty, and refers to the transitive dependency on@cloudflare/workers-typesin@sentry/cloudflare`.

If I use the new wrangler features for import { env } from 'cloudflare:workers'; and then i cmd-click on env - i am bought to the @cloudflare/workers-types definition in the sentry dependency now.

Image

But if I remove the import to sentry, this no longer occurs.

My wrangler version is 4.13.1

My app is based on this template: https://github.com/cloudflare/templates/blob/staging/react-router-postgres-ssr-template

So that's likely a good spot to test an integration.

SlexAxton avatar Apr 30 '25 17:04 SlexAxton

It's also possible that this is some artifact of pnpm too. So I should mention that I'm also using pnpm

SlexAxton avatar Apr 30 '25 17:04 SlexAxton

I think it's possible that it is a pnpm related issue, or rather, a monorepo one.

I have @cloudflare/workers-types installed in a different package that still uses it. So the package exists in my root folder. Then for the @sentry/cloudflare project it's listed as an optional peerDependency. So I think in many cases folks won't run into this unless some other package has installed it. BUT once it's in the node_modules folder, it is loaded along with @sentry/cloudflare and blows away the Env types from ./worker-configuration.d.ts.

I tried a bunch of ways to try to make this go away. I was hopeful that just a line like this in my tsconfig.json would do the trick:

{
  "paths": {
    "@cloudflare/workers-types": "./empty.d.ts"
  }
}

I also tried the overrides functionality in pnpm but couldn't figure out an incantation that worked for me.

Eventually I got a hacky solution, that works for now. Maybe it's helpful to someone else until this is resolved.

I found a unique version of @cloudflare/workers-types in the 4.x range, so that it would meet the peerDependency for @sentry/cloudflare, and installed it to my project in devDependencies. In my case, no other project was using 4.20250430.0

Then I ran pnpm patch @cloudflare/[email protected]

Then I hopped into the folder that it generates for you and patched both index.ts and index.d.ts to just be a single line:

export {};

Once both those files were replaced with that line, I ran the patch-commit command to create the patch:

pnpm patch-commit '/Users/you/your/project/node_modules/.pnpm_patches/@cloudflare/[email protected]'

Then I ran pnpm install to load in the patched version of the dependency. And now my Env variables and cloudflare stuff more generally all resolves to my worker-configuration.d.ts file again.

Definitely a short term fix, but hopefully it unblocks someone!

SlexAxton avatar Apr 30 '25 19:04 SlexAxton

@SlexAxton your setup exactly matches mine. Monorepo, pnpm, recent wrangler upgrade Thanks for posting your patch fix! I've put my sentry integration on hold due to this, but I'll take another look and see if your method works for me too

shmuli9 avatar Apr 30 '25 22:04 shmuli9

I'm curious what happens if you report this to pnpm, perhaps they'll consider it a bug on their side?

Longer term we should try to find a way where we can avoid having the peer dep with @cloudflare/workers-types - relying on generics and inferencing the types passed in structurally should be good enough for the most part.

we still need the dep (and in fact it's what cloudflare themselves recommends for libraries), but I think we can avoid doing it this way.

AbhiPrasad avatar May 01 '25 20:05 AbhiPrasad

Same issue when integrating @sentry/cloudflare and Hono using Bun package manager (in a monorepo).

import * as Sentry from "@sentry/cloudflare";

That's the line that's causing the issue.

MonsterDeveloper avatar May 20 '25 09:05 MonsterDeveloper

@MonsterDeveloper are you also using pnpm? Are you able to provide a reproduction to help us debug this further?

AbhiPrasad avatar May 20 '25 13:05 AbhiPrasad

I think he’s saying he’s not using pnpm, but using bun’s package manager. But bun would use a similar technique in a monorepo to pnpm.

SlexAxton avatar May 20 '25 14:05 SlexAxton

@AbhiPrasad exactly.

I'm using Bun package manager and its workspaces (defined under workspaces in package.json)

Can't provide you with the details for repro, however, I've just tested @sentry/cloudflare on a blank workers app—it does not break the types on a greenfield app.

MonsterDeveloper avatar May 20 '25 14:05 MonsterDeveloper

Hello, I just wanted to 1 up this issue.

I'm using SvelteKit with pnpm. When I follow the install procedure, some Cloudflare types override my own ambient types (app.d.ts in SvelteKit). Sentry support bought me here, I'll keep an eye on it. This is dealbreaker for me, but I'd really like to try Sentry

axel-rock avatar May 20 '25 20:05 axel-rock

@axel-rock are you able to provide us a reproduction? We need to see what exact conditions are causing this issue.

AbhiPrasad avatar May 20 '25 20:05 AbhiPrasad

@AbhiPrasad I wanted to reproduce, so started a fresh SvelteKit project, created a type that can conflict as it does in my current project. And... no issue. So I went for deleting node_modules, and my lock files, and re-installed everything, my types seem to work now

axel-rock avatar May 20 '25 21:05 axel-rock

@AbhiPrasad I wanted to reproduce, so started a fresh SvelteKit project, created a type that can conflict as it does in my current project. And... no issue. So I went for deleting node_modules, and my lock files, and re-installed everything, my types seem to work now

Just tried the same thing, didn't work for me unfortunately :(

MonsterDeveloper avatar May 21 '25 11:05 MonsterDeveloper

I am facing the same issue, including this line breaks the ENV

import * as Sentry from "@sentry/cloudflare";

I first implemented the integration using @cloudflare/pages-plugin-sentry which was working fine, the only problem is, package is deprecated, then I moved to @sentry/cloudflare which is breaking the ENV.

Zura1z avatar May 21 '25 15:05 Zura1z

For pnpm there's a workaround basically overriding @cloudflare/workers-types

I have a pnpm workspace - top level package.json:

{
    // ...
    "overrides": {
      "@cloudflare/workers-types": "link:./packages/empty-types"
    }
  }
}

then the empty-types package.json

{
  "name": "@empty/types",
  "version": "1.0.0"
}

Why this works: As Cloudflare migrates to generated custom types for workers based on wrangler configs many 3rd party libraries still rely on base types. The namespace for generated types becomes polluted by the @cloudflare/workers-types library. With pnpm overrides you can prevent any types from actually being inserted into the type declarations, letting the generated take precedence.

More details on my blog.

jokull avatar May 26 '25 13:05 jokull

I was able to fix the issue by following @jokull's PNPM override suggestion

alexbilbie avatar Jun 02 '25 07:06 alexbilbie

I’ve created a minimal reproduction repo to demonstrate the issue where importing @sentry/cloudflare breaks the Env types generated by Wrangler:

🔗 Repo: https://github.com/aec-craft/hono-sentry-env-issue

This example uses hono, @sentry/cloudflare, and [email protected]. The Env type works fine until I add this line:

import * as Sentry from "@sentry/cloudflare";

As soon as it’s included, typechecking fails - and commenting it out restores proper type behavior. Hopefully this helps others reproduce the problem easily!

Thanks 🙏

Zura1z avatar Jun 18 '25 14:06 Zura1z

Hey @Zura1z - thanks for the reproduction! I'm taking a look now.

AbhiPrasad avatar Jun 18 '25 15:06 AbhiPrasad

I’ve created a minimal reproduction repo to demonstrate the issue where importing @sentry/cloudflare breaks the Env types generated by Wrangler:

🔗 Repo: https://github.com/aec-craft/hono-sentry-env-issue

This example uses hono, @sentry/cloudflare, and [email protected]. The Env type works fine until I add this line:

import * as Sentry from "@sentry/cloudflare";

As soon as it’s included, typechecking fails - and commenting it out restores proper type behavior. Hopefully this helps others reproduce the problem easily!

Thanks 🙏

Hi, I’m also experiencing this issue.

As soon as I add the following line:

import * as Sentry from '@sentry/cloudflare';

TypeScript autocomplete for env.{VAR_NAME} stops working in my Cloudflare Workers project.

I’m using this pattern to infer types from the environment bindings provided by cloudflare:workers:

import { env } from 'cloudflare:workers';

type Env = typeof env;

Then in my Hono app, I extend the context like this:

const app = new Hono<{
  Bindings: Env;
  Variables: {
    databases: DatabaseInstances;
  };
}>();

declare module "hono" {
  interface Bindings {
    env: Env;
  }
  interface Variables {
    databases: DatabaseInstances;
  }
}

Everything works perfectly until I import Sentry. As soon as I add the @sentry/cloudflare import, autocomplete for env.SENTRY_DSN (for exemple) and all other environment variables stops working. It's like the env type gets silently overridden or shadowed.

This seems to be caused by Sentry importing its own version of env types, which messes up the type resolution.

I've also tried installing the dependencies using npm (instead of pnpm) as suggested in the issue comments, and even tested it in a standalone folder with just the backend (not part of a monorepo), but autocomplete is still broken as soon as I import @sentry/cloudflare.

Did you have any ETA on this bug ?

xerosta avatar Jul 06 '25 01:07 xerosta

Hey @xerosta, sorry to hear this causing troubles – we're still working on the PR, you'll be notified here once we have resolved this!

chargome avatar Jul 07 '25 08:07 chargome

Is there any work around for this ?

doraeminemon avatar Jul 12 '25 05:07 doraeminemon

@doraeminemon if you're using pnpm, you can try switching to npm temporarily (?). Furthermore, perhaps https://github.com/getsentry/sentry-javascript/issues/16099#issuecomment-2909681254 helps? Other than that, I'm not aware of a workaround and would recommend waiting on #16704. Sorry for the inconvenience!

Lms24 avatar Jul 14 '25 08:07 Lms24

Hey this is still an issue. @betegon any workarounds? I cant get overrides to work properly in pnpm. Weirdly this didnt cause an issue with another package I have in the same monorepo which uses @cloudflare/workers-types

mattzcarey avatar Aug 13 '25 14:08 mattzcarey

@mattzcarey still on our plate, sorry. Abhi is currently OOO and we'll be on Hackweek next week so might take a bit 😓.

Could you show your package.json? Curious why the override doesn't work for you.

andreiborza avatar Aug 13 '25 16:08 andreiborza

Seeing same issue with Yarn 4

marbemac avatar Aug 15 '25 20:08 marbemac

"overrides": {
  "@cloudflare/workers-types": "link:./packages/empty-types"

then the empty-types package.json

{ "name": "@empty/types", "version": "1.0.0" }

More details on my blog.

@jokull

you don't need a whole 'empty' package, you can just do - to remove the package via pnpm overrides, since pnpm v9.12.0

"overrides": {
  "@cloudflare/workers-types": "-"
}

Glad to see traction on this issue. Lost several frustrating hours on this.

aroman avatar Aug 19 '25 07:08 aroman

Hi, thanks for the workarounds and apologies for the inconvenience. We'll take a look at this more in depth next week.

andreiborza avatar Aug 19 '25 11:08 andreiborza

For pnpm there's a workaround basically overriding @cloudflare/workers-types

I have a pnpm workspace - top level package.json:

{ // ... "overrides": { "@cloudflare/workers-types": "link:./packages/empty-types" } } } then the empty-types package.json

{ "name": "@empty/types", "version": "1.0.0" } Why this works: As Cloudflare migrates to generated custom types for workers based on wrangler configs many 3rd party libraries still rely on base types. The namespace for generated types becomes polluted by the @cloudflare/workers-types library. With pnpm overrides you can prevent any types from actually being inserted into the type declarations, letting the generated take precedence.

More details on my blog.

unfortunately does not work using bun

moesmufti avatar Aug 20 '25 07:08 moesmufti

I want to add Sentry to our Cloudflare/Hono backend but facing the same issue

soufianeelc avatar Aug 30 '25 12:08 soufianeelc