Unit 3: API Development and Server Actions - Practice Quiz

INT257 — Modern Web Application Development 60 Questions
0 Correct 0 Wrong 60 Left
0/60

1 What is the main purpose of a route handler?

Route Handlers Easy
A. To compile CSS files
B. To process requests for a specific URL
C. To store browser history
D. To design the website logo

2 What does REST commonly describe in web development?

REST APIs Easy
A. A style for designing web APIs
B. A format for styling web pages
C. A language for writing databases
D. A tool for compressing images

3 Which HTTP method is commonly used to retrieve data?

HTTP Methods Easy
A. GET
B. PATCH
C. POST
D. DELETE

4 Which HTTP method is commonly used to create new data?

HTTP Methods Easy
A. DELETE
B. POST
C. GET
D. HEAD

5 What does a dynamic route usually contain?

Dynamic Route Handlers Easy
A. A database password
B. A variable path segment
C. A fixed image dimension
D. A CSS color value

6 In a route such as /users/42, what might 42 represent?

Dynamic Route Handlers Easy
A. A request method
B. A user identifier
C. A file extension
D. A response header

7 What does a server receive from a client in a web request?

Request and Response Handling Easy
A. Only database tables
B. A compiled application
C. Request data
D. Only CSS rules

8 What does a server send back after processing a request?

Request and Response Handling Easy
A. A source repository
B. A browser extension
C. A route folder
D. A response

9 Which status code usually means that a request succeeded?

Request and Response Handling Easy
A. 404
B. 500
C. 200
D. 301

10 What is a server action designed to do?

Server Actions Easy
A. Run specific logic on the server
B. Control the user's keyboard
C. Draw icons on a canvas
D. Change the browser theme

11 Which task is a suitable use for a server action?

Server Actions Easy
A. Changing screen brightness
B. Playing a local audio file
C. Saving submitted form data
D. Selecting a browser tab

12 What is the purpose of a form in a web application?

Form Handling Easy
A. To define database indexes
B. To collect user input
C. To cache network requests
D. To generate server logs

13 Which event commonly occurs when a user sends a form?

Form Handling Easy
A. Hover
B. Resize
C. Submit
D. Scroll

14 What is the main purpose of form validation?

Form Validation Easy
A. To check whether input is acceptable
B. To remove all response headers
C. To increase image resolution
D. To rename the application

15 Which input would usually fail validation for an email field?

Form Validation Easy
A. user99@site.org
B. alex.example.com
C. contact@school.edu
D. alex@example.com

16 Which HTML control is commonly used to select a file?

File Upload Easy
A. A link with type document
B. An input with type file
C. A paragraph with type upload
D. A button with type image

17 Which object commonly represents an uploaded file in web APIs?

File Upload Easy
A. File
B. Color
C. Route
D. Cookie

18 What is a data mutation?

Data Mutations Easy
A. A request that only reads data
B. A browser window resize
C. An operation that changes stored data
D. A style applied to a button

19 What is an optimistic UI update?

Optimistic UI Updates Easy
A. Displaying only server error messages
B. Waiting for the server before changing anything
C. Deleting the interface after every request
D. Updating the interface before server confirmation

20 What should an application do if an optimistic update fails on the server?

Optimistic UI Updates Easy
A. Revert or correct the displayed state
B. Delete unrelated application data
C. Refresh the user's operating system
D. Ignore the failure permanently

21 A route handler receives a POST /api/orders request containing JSON. Which sequence is most appropriate for creating the order?

Route Handlers Medium
A. Redirect the request and ignore the submitted data
B. Use a GET response before saving the order
C. Parse the body, validate it, save the order, and return a status
D. Return the request body without parsing or validation

22 A route handler must return a JSON object containing { "status": "ok" }. Which response is most suitable?

Route Handlers Medium
A. A plain-text response with a 404 status
B. A JSON response with a 200 status
C. An HTML response with a 201 status
D. A redirect response with a 204 status

23 Which endpoint design best follows REST conventions for retrieving one product with ID 42?

REST APIs Medium
A. GET /api/products/42
B. GET /api/getProduct?id=42
C. POST /api/products/42
D. GET /api/product-action/42

24 A client requests a collection of published articles with pagination. Which design is most appropriate?

REST APIs Medium
A. POST /api/articles/list/published/2
B. GET /api/articles?status=published&page=2
C. GET /api/fetchPublishedArticlesPageTwo
D. PUT /api/articles?status=published&page=2

25 A user changes the title of an existing article and sends the complete updated article representation. Which HTTP method is the best fit?

HTTP Methods Medium
A. PATCH
B. DELETE
C. PUT
D. POST

26 Which status code best indicates that a new account was successfully created by a POST request?

HTTP Methods Medium
A. 204 No Content
B. 202 Accepted
C. 200 OK
D. 201 Created

27 A dynamic route is defined as /api/users/[id]. A request arrives at /api/users/73. What should the handler use to identify the requested user?

Dynamic Route Handlers Medium
A. The request method with value 73
B. The response header id with value 73
C. The query parameter user with value 73
D. The route parameter id with value 73

28 A request to /api/posts/abc cannot find a post with ID abc. What should the dynamic route handler normally return?

Dynamic Route Handlers Medium
A. A 201 Created response
B. A 302 Found response
C. A 204 No Content response
D. A 404 Not Found response

29 A client sends invalid JSON to an endpoint that expects a JSON body. How should the handler respond?

Request and Response Handling Medium
A. Retry parsing until valid JSON appears
B. Treat the body as valid form data
C. Return a 400 Bad Request response
D. Return a 200 OK response with empty data

30 An API endpoint returns a list of users but must prevent browsers and intermediaries from reusing stale data. Which response behavior is most relevant?

Request and Response Handling Medium
A. Set appropriate cache-control headers
B. Change the response body to HTML
C. Use POST instead of GET
D. Store the users in a URL fragment

31 A form invokes a server action that inserts a record into a database. Which security practice is still required?

Server Actions Medium
A. Validate authorization inside the server action
B. Allow the client to choose the acting user ID
C. Expose database credentials to the browser
D. Trust the form because it came from the application

32 After a server action updates a product name, the page still displays the old cached product data. What is the most appropriate follow-up?

Server Actions Medium
A. Convert the action into a client-only function
B. Increase the form submission timeout
C. Revalidate or refresh the affected data
D. Hide the product name after submission

33 A form submits a username and a profile image to a server action. Which encoding is needed to transmit both fields correctly?

Form Handling Medium
A. multipart/form-data
B. application/json only
C. application/x-url-path
D. text/plain only

34 A form should show a pending indicator while its server action is running and then disable the submit button. What is the best approach?

Form Handling Medium
A. Disable the button permanently after rendering
B. Wait for a browser navigation before showing feedback
C. Track the action's pending state in the UI
D. Reload the page repeatedly during submission

35 A registration form checks that an email is present in the browser. Why must the server repeat this validation?

Form Validation Medium
A. Client-side checks can be bypassed
B. Client-side validation changes database schemas
C. Server validation makes passwords unnecessary
D. Browsers cannot display validation messages

36 A form requires a product quantity to be an integer from 1 through 10. Which server-side rule correctly enforces this requirement?

Form Validation Medium
A. Check that the parsed value is an integer and lies between 1 and 10
B. Round every submitted value before storing it
C. Check only that the submitted value is not empty
D. Accept any string containing at least one digit

37 An upload endpoint accepts profile images. Which validation combination provides the strongest basic protection?

File Upload Medium
A. Allow all files and validate them after public access
B. Check only whether the file has an extension
C. Check size, MIME type, extension, and generated storage name
D. Trust the filename and store it directly

38 A user uploads a file named ../../avatar.png. What is the safest storage behavior?

File Upload Medium
A. Remove only the first two dots from the filename
B. Store the file using the full submitted path
C. Join the filename directly with the upload directory
D. Ignore the supplied path and generate a safe filename

39 A delete operation is requested for an invoice that does not exist. Which behavior is generally most useful for an idempotent API?

Data Mutations Medium
A. Return success or a consistent not-found result by API design
B. Create a new invoice with the requested identifier
C. Return 201 Created for every delete request
D. Randomly delete another invoice

40 Two users edit the same document. Which technique best helps prevent one update from silently overwriting a newer update?

Data Mutations Medium
A. Disable validation for simultaneous requests
B. Use version checks or optimistic concurrency control
C. Store every update under the same timestamp
D. Always accept the request that arrives last

41 A Next.js App Router project contains app/reports/page.tsx. A developer adds app/reports/route.ts to expose a JSON endpoint at /reports, and the build reports a route conflict. Which change correctly resolves the conflict while preserving both interfaces?

Route Handlers Hard
A. Export the handler from page.tsx alongside the page's default export
B. Rename the handler to app/reports/handler.ts and keep the /reports URL
C. Move the handler to app/reports/api/route.ts and expose it at /reports/api
D. Keep both files and add a rewrite that selects the page or handler from the request's Accept header

42 An API paginates orders sorted by createdAt DESC. New orders may share timestamps and may be inserted while clients paginate. Which cursor design most reliably prevents skipped or duplicated records?

REST APIs Hard
A. Use the current page number and a fixed server-side page size
B. Use only the createdAt timestamp of the final returned order
C. Use the total order count followed by the current numeric offset
D. Use an opaque cursor containing both createdAt and the unique order ID

43 A client times out after sending a payment-creation request and cannot determine whether the server committed it. Which API design best permits a safe retry without creating a second payment?

HTTP Methods Hard
A. Send GET with the payment fields encoded as query parameters
B. Send POST repeatedly and compare payment timestamps afterward
C. Send POST with an idempotency key stored under a unique constraint
D. Send PATCH because all partial updates are inherently idempotent

44 A handler is defined at app/api/docs/[[...slug]]/route.ts. Assuming the route parameters have been resolved, what values should it expect for requests to /api/docs and /api/docs/guides/install?

Dynamic Route Handlers Hard
A. slug is [] first and "guides/install" second
B. slug is ["docs"] first and ["docs", "guides", "install"] second
C. slug is undefined first and ["guides", "install"] second
D. slug is "docs" first and ["guides", "install"] second

45 A Route Handler must verify an HMAC over the exact raw request body and then parse the same body as JSON. Which approach is valid with the Fetch Request API?

Request and Response Handling Hard
A. Call request.text() and then call request.json() on the same request
B. Read request.bodyUsed, reset it to false, and then parse the body again
C. Clone the request before consumption, then read one body as text and the other as JSON
D. Parse the body as JSON first, serialize the resulting object, and assume the serialization always reproduces the exact signed bytes

46 A Route Handler must set two cookies with different attributes in one response. Which implementation preserves both cookies correctly?

Request and Response Handling Hard
A. Join both cookie strings with commas in one Set-Cookie header
B. Use NextResponse.cookies.set once for each cookie before returning
C. Call headers.set("Set-Cookie", ...) twice on one Headers object
D. Return the first cookie in a header and the second cookie in the JSON body

47 A Server Action called by an authenticated page receives accountId from submitted form data and deletes that account. What security check is essential inside the action?

Server Actions Hard
A. Trust the ID because the form was rendered only for authenticated users
B. Accept the ID when it matches a hidden field signed only by client-side JavaScript
C. Verify that the action request originated from a React Client Component
D. Authorize the current server-side identity for the submitted accountId

48 A Server Action has the signature updateUser(userId, formData). Which expression correctly supplies userId while allowing <form action={...}> to provide the submitted FormData?

Form Handling Hard
A. const action = updateUser.bind(null, formData, userId) so the browser can replace the bound FormData during submission
B. const action = updateUser.bind(null, userId)
C. const action = () => updateUser(formData, userId)
D. const action = updateUser.bind(formData, userId)

49 A registration form performs schema validation in the browser. The associated Server Action writes directly to the database without validating again. Which revision provides the correct trust boundary and supports field-level errors?

Form Validation Hard
A. Rely on HTML constraints because invalid forms cannot be submitted by browsers
B. Validate only a hidden Boolean indicating that client validation succeeded
C. Parse FormData with the schema in the action and return structured field errors
D. Sanitize database error messages and use them as the primary validation mechanism

50 A Route Handler accepts multi-gigabyte uploads, but await request.formData() followed by await file.arrayBuffer() exhausts memory. Which architecture best addresses the problem?

File Upload Hard
A. Trust Content-Length completely and buffer the body only when that header claims the file is within the configured limit
B. Stream bytes to storage while enforcing incremental size and type limits
C. Increase the JavaScript heap and retain the upload until validation completes
D. Convert the entire file to Base64 before writing it to object storage

51 An endpoint transfers credits by decrementing one balance, incrementing another, and inserting a ledger entry. Which implementation preserves consistency when a database operation fails halfway through?

Data Mutations Hard
A. Run all three writes concurrently with Promise.all
B. Update the balances first and asynchronously reconcile the ledger later
C. Execute all three writes in one database transaction
D. Retry only the ledger insertion after returning an error

52 A user renames the same item twice before the first mutation finishes. The first request fails after the second optimistic rename has been displayed. What rollback strategy avoids overwriting the newer state?

Optimistic UI Updates Hard
A. Always restore the value captured before the first request
B. Reload the entire application whenever either request settles
C. Rollback only if the current optimistic version matches the failed operation
D. Apply failed rollbacks in request-start order regardless of completion order

53 A browser sends a cross-origin PUT request with Content-Type: application/json and an Authorization header. The API's PUT handler is correct, but the browser never sends the actual request. What is the most likely missing behavior?

Route Handlers Hard
A. An OPTIONS handler returning the required CORS allow headers
B. A GET handler redirecting the browser to the canonical API URL
C. A HEAD handler returning the same body as the PUT handler
D. A middleware rule that converts every cross-origin PUT request into a same-origin form submission

54 A POST /exports request starts a long-running export and returns before processing is complete. Which response most accurately represents the REST semantics?

REST APIs Hard
A. 204 No Content with a Retry-After request header
B. 304 Not Modified with the identifier of the queued operation
C. 201 Created with the completed export file in the body
D. 202 Accepted with a location for checking job status

55 Two administrators retrieve version 7 of a document. One updates it to version 8; the other then submits changes based on version 7. Which HTTP mechanism best prevents the second update from silently overwriting the first?

HTTP Methods Hard
A. Require Cache-Control: no-store and return 409 for every update
B. Require If-None-Match with * and return 304 on mismatch
C. Require Last-Modified in the request body and return 202 on mismatch
D. Require If-Match with the version 7 ETag and return 412 on mismatch

56 A multi-tenant handler uses /api/tenants/[tenantId]/invoices/[invoiceId]. The session proves the user belongs to tenant A, but the URL specifies tenant B. What should the handler do before retrieving the invoice?

Dynamic Route Handlers Hard
A. Reject access unless the identity is authorized for URL tenant B
B. Retrieve by invoiceId alone because invoice identifiers are globally unique
C. Trust tenant B because dynamic parameters are generated by the framework router
D. Replace tenant B with tenant A and continue without reporting it

57 A successful DELETE operation has no representation to return. Which response is valid according to HTTP semantics?

Request and Response Handling Hard
A. Return status 200 while declaring a nonzero body length but sending no body
B. Return status 204 with no response body
C. Return status 204 with a JSON confirmation body
D. Return status 304 with an empty response body

58 A Server Action wraps its mutation and redirect("/dashboard") inside a broad try...catch. Successful submissions unexpectedly return the generic error state instead of navigating. What is the correct fix?

Server Actions Hard
A. Run the redirect in finally so it executes after both success and failure
B. Replace redirect with revalidatePath inside the catch block
C. Catch the redirect and return its error object to the Client Component
D. Call redirect after the try...catch once the mutation succeeds

59 A client optimistically inserts comments using temporary IDs. The server returns the persisted comment with a canonical ID and normalized text. What is the correct reconciliation behavior?

Optimistic UI Updates Hard
A. Discard the server response and retain only the optimistic representation
B. Replace the matching temporary entry with the returned canonical comment
C. Clear every comment and wait for a later full-page cache revalidation
D. Append the canonical comment and leave the temporary entry unchanged

60 An upload endpoint stores files using the client-provided File.name under a public directory. Which design best mitigates path traversal, collisions, and misleading file-type metadata?

File Upload Hard
A. Generate a server-side storage key and validate content independently of the filename
B. Preserve the full filename because multipart parsers normalize every platform-specific path and guarantee that duplicate names cannot overwrite files
C. Remove ../ once from the filename and trust the remaining extension
D. Hash only the original filename and continue trusting its declared MIME type