Skip to content

Commit

Permalink
get nonce out of express and into RR
Browse files Browse the repository at this point in the history
  • Loading branch information
kentcdodds committed Mar 7, 2025
1 parent 97c7611 commit d30802a
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 18 deletions.
12 changes: 4 additions & 8 deletions app/entry.server.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import crypto from 'node:crypto'
import { PassThrough } from 'node:stream'
import { styleText } from 'node:util'
import { contentSecurity } from '@nichtsam/helmet/content'
Expand Down Expand Up @@ -26,13 +27,8 @@ const MODE = process.env.NODE_ENV ?? 'development'
type DocRequestArgs = Parameters<HandleDocumentRequestFunction>

export default async function handleRequest(...args: DocRequestArgs) {
const [
request,
responseStatusCode,
responseHeaders,
reactRouterContext,
loadContext,
] = args
const [request, responseStatusCode, responseHeaders, reactRouterContext] =
args
const { currentInstance, primaryInstance } = await getInstanceInfo()
responseHeaders.set('fly-region', process.env.FLY_REGION ?? 'unknown')
responseHeaders.set('fly-app', process.env.FLY_APP_NAME ?? 'unknown')
Expand All @@ -47,7 +43,7 @@ export default async function handleRequest(...args: DocRequestArgs) {
? 'onAllReady'
: 'onShellReady'

const nonce = loadContext.cspNonce?.toString() ?? ''
const nonce = crypto.randomBytes(16).toString('hex')
return new Promise(async (resolve, reject) => {
let didError = false
// NOTE: this timing will only include things that are rendered in the shell
Expand Down
11 changes: 1 addition & 10 deletions server/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import crypto from 'node:crypto'
import { styleText } from 'node:util'
import { helmet } from '@nichtsam/helmet/node-http'
import { createRequestHandler } from '@react-router/express'
Expand Down Expand Up @@ -110,11 +109,6 @@ app.use(
}),
)

app.use((_, res, next) => {
res.locals.cspNonce = crypto.randomBytes(16).toString('hex')
next()
})

// When running tests or running in development, we want to effectively disable
// rate limiting because playwright tests are very fast and we don't want to
// have to wait for the rate limit to reset between tests.
Expand Down Expand Up @@ -201,10 +195,7 @@ if (!ALLOW_INDEXING) {
app.all(
'*',
createRequestHandler({
getLoadContext: (_: any, res: any) => ({
cspNonce: res.locals.cspNonce,
serverBuild: getBuild(),
}),
getLoadContext: () => ({ serverBuild: getBuild() }),
mode: MODE,
build: async () => {
const { error, build } = await getBuild()
Expand Down

0 comments on commit d30802a

Please sign in to comment.