Skip to content

Commit a110e0b

Browse files
authored
Fix app staging header request guard (#63511)
Copilot-Session: 7c52b57f-2c29-4aa1-8233-99d0d6e13571
1 parent 886e294 commit a110e0b

2 files changed

Lines changed: 58 additions & 1 deletion

File tree

‎src/frame/pages/app.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ MyApp.getInitialProps = async (appContext: AppContext) => {
148148
}
149149
}
150150
}
151-
const headerValue = req.headers['x-ong-external-url']
151+
const headerValue = req?.headers['x-ong-external-url']
152152
const stagingName = (typeof headerValue === 'string' ? headerValue : headerValue?.[0])?.match(
153153
/staging-(\w+)\./,
154154
)?.[1]

‎src/frame/tests/app.ts‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import { IncomingMessage, type IncomingHttpHeaders } from 'node:http'
2+
import { Socket } from 'node:net'
3+
import type { AppContext } from 'next/app'
4+
import { describe, expect, test, vi } from 'vitest'
5+
6+
import MyApp from '@/frame/pages/app'
7+
8+
vi.mock('@primer/react', () => ({
9+
ThemeProvider: ({ children }: { children: unknown }) => children,
10+
}))
11+
12+
type TestRequest = NonNullable<AppContext['ctx']['req']> & {
13+
context: Record<string, unknown>
14+
}
15+
16+
function createRequest(headers: IncomingHttpHeaders): TestRequest {
17+
const req = new IncomingMessage(new Socket()) as TestRequest
18+
req.context = {}
19+
req.headers = headers
20+
return req
21+
}
22+
23+
function createAppContext(req?: TestRequest): AppContext {
24+
const Component = () => null
25+
26+
return {
27+
AppTree: Component,
28+
Component,
29+
ctx: {
30+
AppTree: Component,
31+
pathname: '/',
32+
query: {},
33+
req,
34+
},
35+
router: {} as AppContext['router'],
36+
}
37+
}
38+
39+
describe('MyApp.getInitialProps', () => {
40+
test('handles client-side error renders without a request', async () => {
41+
const props = await MyApp.getInitialProps(createAppContext())
42+
43+
expect(props.stagingName).toBeUndefined()
44+
})
45+
46+
test('sets the staging name from the request header', async () => {
47+
const props = await MyApp.getInitialProps(
48+
createAppContext(
49+
createRequest({
50+
'x-ong-external-url': 'https://docs-staging-cedar.example.com/',
51+
}),
52+
),
53+
)
54+
55+
expect(props.stagingName).toBe('cedar')
56+
})
57+
})

0 commit comments

Comments
 (0)