File size: 7,884 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
/* eslint-disable jest/no-standalone-expect */
import { nextTestSetup } from 'e2e-utils'
import { createRequestTracker } from 'e2e-utils/request-tracker'
import { retry } from 'next-test-utils'
import { outdent } from 'outdent'

describe('unrecognized server actions', () => {
  const { next, isNextDeploy, isNextDev } = nextTestSetup({
    files: __dirname,
  })

  let cliOutputPosition: number = 0
  beforeEach(() => {
    cliOutputPosition = next.cliOutput.length
  })
  const getLogs = () => {
    return next.cliOutput.slice(cliOutputPosition)
  }

  // This is disabled when deployed because the 404 page will be served as a static route
  // which will not support POST requests, and will return a 405 instead.
  if (!isNextDeploy) {
    it('should 404 when POSTing a non-server-action request to a nonexistent page', async () => {
      const res = await next.fetch('/non-existent-route', {
        method: 'POST',
        headers: {
          'content-type': 'application/x-www-form-urlencoded',
        },
        body: 'foo=bar',
      })

      const cliOutput = getLogs()
      expect(cliOutput).not.toContain('TypeError')
      expect(cliOutput).not.toContain(
        'Missing `origin` header from a forwarded Server Actions request'
      )
      expect(res.status).toBe(404)
    })

    it.each([
      {
        // encodeReply encodes simple args as plaintext.
        name: 'plaintext',
        request: {
          contentType: 'text/plain;charset=UTF-8',
          body: '{}',
        },
      },
      {
        // encodeReply encodes complex args as FormData.
        // this body is empty and wouldn't match how react encodes an action, but it should be rejected
        // before we even get to parsing the FormData, so it doesn't really matter.
        name: 'form-data/multipart',
        request: {
          body: new FormData(),
        },
      },
      {
        // we never use urlencoded actions, but we currently have codepaths for it in `handleAction`,
        // so might as well test them.
        name: 'urlencoded',
        request: {
          contentType: 'application/x-www-form-urlencoded',
          body: 'foo=bar',
        },
      },
    ])(
      'should 404 when POSTing a server action with an unrecognized id to a nonexistent page: $name',
      async ({ request: { contentType, body } }) => {
        const res = await next.fetch('/non-existent-route', {
          method: 'POST',
          headers: {
            'next-action': '123',
            ...(contentType ? { 'content-type': contentType } : undefined),
          },
          // @ts-expect-error: node-fetch types don't seem to like FormData
          body,
        })

        expect(res.status).toBe(404)

        const cliOutput = getLogs()
        expect(cliOutput).not.toContain('TypeError')
        expect(cliOutput).not.toContain(
          'Missing `origin` header from a forwarded Server Actions request'
        )
        expect(cliOutput).toInclude(outdent`
          Failed to find Server Action "123". This request might be from an older or newer deployment.
          Read more: https://nextjs.org/docs/messages/failed-to-find-server-action
        `)
      }
    )
  }

  describe.each(['nodejs', 'edge'])(
    'should error and log a warning when submitting a server action with an unrecognized ID - %s',
    (runtime) => {
      const testUnrecognizedActionSubmission = async ({
        formId,
        disableJavaScript,
      }: {
        formId: string
        disableJavaScript: boolean
      }) => {
        const browser = await next.browser(`/${runtime}/unrecognized-action`, {
          disableJavaScript,
        })
        const requestTracker = createRequestTracker(browser)

        const [_, response] = await requestTracker.captureResponse(
          async () =>
            await browser
              .elementByCss(`form#${formId} button[type="submit"]`)
              .click(),
          {
            request: {
              method: 'POST',
              pathname: `/${runtime}/unrecognized-action`,
            },
          }
        )

        if (!disableJavaScript) {
          // A fetch action, sent via the router.
          expect(response.status()).toBe(404)
          // NOTE: we cannot validate the response text, because playwright hangs on `response.text()` for some reason.
          expect(response.headers()['content-type']).toStartWith('text/plain')

          // The submission should throw and trigger our error boundary.
          expect(await browser.elementByCss(`#error-boundary`).text()).toMatch(
            /Error boundary: Server Action ".+?" was not found on the server\./
          )

          // We responded with a 404, but we shouldn't trigger a not-found (either a custom or a default one)
          expect(await browser.elementByCss('body').text()).not.toContain(
            'Not found'
          )
          expect(await browser.elementByCss('body').text()).not.toContain(
            'my-not-found'
          )

          if (!isNextDeploy) {
            await retry(async () =>
              expect(getLogs()).toInclude(outdent`
              Failed to find Server Action "decafc0ffeebad01". This request might be from an older or newer deployment.
              Read more: https://nextjs.org/docs/messages/failed-to-find-server-action
            `)
            )
          }
        } else {
          // An MPA action, sent without JS.

          if (isNextDeploy) {
            // FIXME: When deployed to vercel, the request is logged as a 500, but returns a 405.
            // We also don't seem to display the error page correctly
            expect(response.status()).toBe(405)
            expect(response.headers()['content-type']).toStartWith('text/html')
          } else {
            // FIXME: Currently, an unrecognized id in an MPA action results in a 500.
            // This is not ideal, and ignores all nested `error.js` files, only showing the topmost one.
            expect(response.status()).toBe(500)
            expect(response.headers()['content-type']).toStartWith('text/html')
            // In dev, the 500 page doesn't have any SSR'd html, so it won't show anything without JS.
            if (!isNextDev) {
              expect(await browser.elementByCss('body').text()).toContain(
                'Internal Server Error'
              )
            }

            if (!isNextDeploy) {
              // FIXME: For an MPA action, the logs currently show the error thrown by React instead of our custom message with a link to a docs page.
              await retry(async () =>
                expect(getLogs()).toInclude(
                  `Error: Could not find the module "decafc0ffeebad01" in the React Server Manifest. This is probably a bug in the React Server Components bundler`
                )
              )
            }
          }
        }
      }

      it.each([
        {
          description: 'js enabled',
          disableJavaScript: false,
        },
        {
          description: 'js disabled',
          disableJavaScript: true,
        },
      ])(
        'server action invoked via form - $description',
        async ({ disableJavaScript }) => {
          await testUnrecognizedActionSubmission({
            formId: 'form-direct',
            disableJavaScript,
          })
        }
      )

      // these forms rely on client-side JS, so we can't test them with JS disabled
      it.each([
        {
          description: 'with simple argument',
          formId: 'form-simple-argument',
        },
        {
          description: 'with complex argument',
          formId: 'form-complex-argument',
        },
      ])('server action invoked from JS - $description', async ({ formId }) => {
        await testUnrecognizedActionSubmission({
          formId,
          disableJavaScript: false,
        })
      })
    }
  )
})