Description
Deploying @sentry/react-router to Cloudflare Workers is currently not supported out of the box. However, this issue provides a workaround for making it work.
Support renderToReadableStream
The react-router SDK is currently using renderToPipeableStream which is a Node-only API. For react-router to be able to inject the HTML meta tags, this code needs to be adapted to use renderToReadableStream.
Current Workaround
Wrap the handler with withSentry from @sentry/cloudflare:
// in entry.worker.tsimporttype{unstable_InitialContext}from"react-router";import{createRequestHandler,unstable_createContext}from"react-router";import*asbuildfrom"virtual:react-router/server-build";import*asSentryfrom"@sentry/cloudflare";constCloudflareContext=unstable_createContext<{env: Cloudflare.Env;ctx: ExecutionContext;cf?: RequestInitCfProperties;}>();exportdefaultSentry.withSentry(()=>({/* Sentry config options */}),{asyncfetch(request: Request,env: Cloudflare.Env,ctx: ExecutionContext){constcontext: unstable_InitialContext=newMap();context.set(CloudflareContext,{ env, ctx,cf: request.cf});returnawaithandler(request,context);},}satisfiesExportedHandler<Cloudflare.Env>,);Now, create a function to include the HTML meta tags (like here) and inject them into the returned body:
// in app/entry.server.tsximport{renderToReadableStream}from"react-dom/server";import{getTraceMetaTags,getTraceData,getClient}from"@sentry/core";functiongetWebMetaTagTransformer(): TransformStream<Uint8Array,Uint8Array>{constheadClosingTag="</head>";constdecoder=newTextDecoder();constencoder=newTextEncoder();returnnewTransformStream({transform(chunk,controller){consthtml=decoder.decode(chunk);if(html.includes(headClosingTag)){constmodifiedHtml=html.replace(headClosingTag,`${getTraceMetaTags()}${headClosingTag}`,);controller.enqueue(encoder.encode(modifiedHtml));return;}controller.enqueue(chunk);},});}exportdefaultasyncfunctionhandleRequest(/* .... */){// ...constbody=awaitrenderToReadableStream(/* ... */)constsentryTransformer=getWebMetaTagTransformer();consttransformedBody=body.pipeThrough(sentryTransformer);returnnewResponse(transformedBody,{headers: responseHeaders,status: responseStatusCode,});}
Description
Deploying
@sentry/react-routerto Cloudflare Workers is currently not supported out of the box. However, this issue provides a workaround for making it work.Support
renderToReadableStreamThe react-router SDK is currently using
renderToPipeableStreamwhich is a Node-only API. For react-router to be able to inject the HTML meta tags, this code needs to be adapted to userenderToReadableStream.Current Workaround
Wrap the handler with
withSentryfrom@sentry/cloudflare:Now, create a function to include the HTML meta tags (like here) and inject them into the returned body: