Skip to content

[React-Router Framework]: Add Cloudflare support #17334

Description

@s1gr1d

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,});}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions