Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## [Unreleased]

### Added

(plugin-cloudflare-workers): Add initial support for Cloudflare Workers [#2643](https://github.com/bugsnag/bugsnag-js/pull/2643)

### Fixed

(plugin-server-session) Delay session tracker initialization until first use [#2642](https://github.com/bugsnag/bugsnag-js/pull/2642)
Expand Down
6 changes: 5 additions & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,10 @@ module.exports = {
clearMocks: true,
modulePathIgnorePatterns: ['.verdaccio', 'fixtures']
}),
project('react native cli', ['react-native-cli'], { testEnvironment: 'node' })
project('react native cli', ['react-native-cli'], { testEnvironment: 'node' }),
project('cloudflare-workers', ['plugin-cloudflare-workers'], {
testEnvironment: 'node',
setupFilesAfterEnv: ['<rootDir>/packages/plugin-cloudflare-workers/test/setup.ts']
})
]
}
44 changes: 42 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

19 changes: 19 additions & 0 deletions packages/plugin-cloudflare-workers/LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) Bugsnag, https://www.bugsnag.com/

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
7 changes: 7 additions & 0 deletions packages/plugin-cloudflare-workers/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# @bugsnag/plugin-cloudflare-workers

A [@bugsnag/js](https://github.com/bugsnag/bugsnag-js) plugin for capturing errors in Cloudflare Workers.

## License

This package is free software released under the MIT License. See [LICENSE.txt](./LICENSE.txt) for details.
32 changes: 32 additions & 0 deletions packages/plugin-cloudflare-workers/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"name": "@bugsnag/plugin-cloudflare-workers",
"version": "8.6.0",
"main": "src/index.js",
"types": "types/bugsnag-plugin-cloudflare-workers.d.ts",
"description": "Cloudflare Workers support for @bugsnag/js",
"homepage": "https://www.bugsnag.com/",
"repository": {
"type": "git",
"url": "git@github.com:bugsnag/bugsnag-js.git"
},
"publishConfig": {
"access": "public"
},
"files": [
"src",
"types"
],
"author": "Bugsnag",
"license": "MIT",
"dependencies": {
"@bugsnag/in-flight": "^8.6.0",
"@bugsnag/plugin-browser-session": "^8.6.0"
},
"devDependencies": {
"@bugsnag/core": "^8.6.0",
"@cloudflare/workers-types": "^4.20251213.0"
},
"peerDependencies": {
"@bugsnag/core": "^8.0.0"
}
}
116 changes: 116 additions & 0 deletions packages/plugin-cloudflare-workers/src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
const bugsnagInFlight = require('@bugsnag/in-flight')
const BugsnagPluginBrowserSession = require('@bugsnag/plugin-browser-session')

const SERVER_PLUGIN_NAMES = ['express', 'koa', 'restify', 'hono']
const isServerPluginLoaded = client => SERVER_PLUGIN_NAMES.some(name => client.getPlugin(name))

const extractRequestInfo = (request) => {
if (!request) return {}

const url = new URL(request.url)

const info = {
url: request.url,
path: url.pathname,
httpMethod: request.method,
headers: Object.fromEntries(request.headers),
query: url.searchParams.size > 0 ? Object.fromEntries(url.searchParams) : undefined,
clientIp: request.headers.get('Cf-Connecting-IP') || request.headers.get('X-Forwarded-For') || undefined
}

return info
}

const getRequestAndMetadataFromReq = (request) => {
const requestInfo = extractRequestInfo(request)

return {
metadata: requestInfo,
request: {
clientIp: requestInfo.clientIp,
headers: requestInfo.headers,
httpMethod: requestInfo.httpMethod,
url: requestInfo.url
}
}
}

const BugsnagPluginCloudflareWorkers = {
name: 'cloudflareWorkers',

load (client) {
bugsnagInFlight.trackInFlight(client)
client._loadPlugin(BugsnagPluginBrowserSession)

// Reset the app duration between invocations, if the plugin is loaded
const appDurationPlugin = client.getPlugin('appDuration')

if (appDurationPlugin) {
appDurationPlugin.reset()
}

return {
createHandler ({ flushTimeoutMs = 2000 } = {}) {
return wrapHandler.bind(null, client, flushTimeoutMs)
}
}
}
}

function wrapHandler (client, flushTimeoutMs, handler) {
return async function (request, env, ctx) {
// Add request metadata via onError callback so server plugins can override
// Only add metadata if no server plugin is loaded
if (!isServerPluginLoaded(client)) {
client.addOnError((event) => {
const { metadata, request: requestData } = getRequestAndMetadataFromReq(request)
event.request = { ...event.request, ...requestData }
event.addMetadata('request', metadata)
}, true)
}

// Track sessions if autoTrackSessions is enabled and no server plugin is loaded
if (client._config.autoTrackSessions && !isServerPluginLoaded(client)) {
client.startSession()
}

try {
return await handler(request, env, ctx)
} catch (err) {
if (client._config.autoDetectErrors && client._config.enabledErrorTypes.unhandledExceptions) {
const handledState = {
severity: 'error',
unhandled: true,
severityReason: { type: 'unhandledException' }
}

const event = client.Event.create(err, true, handledState, 'cloudflare workers plugin', 1)

client._notify(event)
}

throw err
} finally {
// Use ctx.waitUntil to ensure flush completes even after response is returned
// This is critical for Cloudflare Workers as they can terminate immediately
if (ctx && typeof ctx.waitUntil === 'function') {
ctx.waitUntil(
bugsnagInFlight.flush(flushTimeoutMs).catch(err => {
client._logger.error(`Delivery may be unsuccessful: ${err.message}`)
})
)
} else {
try {
await bugsnagInFlight.flush(flushTimeoutMs)
} catch (err) {
client._logger.error(`Delivery may be unsuccessful: ${err.message}`)
}
}
}
}
}

module.exports = BugsnagPluginCloudflareWorkers

// add a default export for ESM modules without interop
module.exports.default = module.exports
Loading