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 design the website logo
B. To compile CSS files
C. To process requests for a specific URL
D. To store browser history

2 What does REST commonly describe in web development?

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

3 Which HTTP method is commonly used to retrieve data?

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

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 fixed image dimension
B. A variable path segment
C. A CSS color value
D. A database password

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

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

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

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

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

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

9 Which status code usually means that a request succeeded?

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

10 What is a server action designed to do?

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

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

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

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

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

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

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

14 What is the main purpose of form validation?

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

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

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

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

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

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

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

18 What is a data mutation?

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

19 What is an optimistic UI update?

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

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

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

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. Use a GET response before saving the order
B. Redirect the request and ignore the submitted data
C. Return the request body without parsing or validation
D. Parse the body, validate it, save the order, and return a status

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

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

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

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

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

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

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. PUT
B. DELETE
C. POST
D. PATCH

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. 201 Created
C. 202 Accepted
D. 200 OK

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 response header id with value 73
B. The request method 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 404 Not Found response
B. A 201 Created response
C. A 204 No Content response
D. A 302 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. Return a 400 Bad Request response
C. Treat the body as valid form data
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. Use POST instead of GET
B. Set appropriate cache-control headers
C. Store the users in a URL fragment
D. Change the response body to HTML

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

Server Actions Medium
A. Expose database credentials to the browser
B. Allow the client to choose the acting user ID
C. Validate authorization inside the server action
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. Increase the form submission timeout
B. Revalidate or refresh the affected data
C. Convert the action into a client-only function
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. application/x-url-path
B. text/plain only
C. multipart/form-data
D. application/json 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. Track the action's pending state in the UI
B. Disable the button permanently after rendering
C. Wait for a browser navigation before showing feedback
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. Browsers cannot display validation messages
C. Client-side validation changes database schemas
D. Server validation makes passwords unnecessary

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 only that the submitted value is not empty
B. Check that the parsed value is an integer and lies between 1 and 10
C. Accept any string containing at least one digit
D. Round every submitted value before storing it

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. Ignore the supplied path and generate a safe filename
B. Join the filename directly with the upload directory
C. Remove only the first two dots from the filename
D. Store the file using the full submitted path

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. Create a new invoice with the requested identifier
B. Return success or a consistent not-found result by API design
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. Use version checks or optimistic concurrency control
B. Always accept the request that arrives last
C. Store every update under the same timestamp
D. Disable validation for simultaneous requests

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. Rename the handler to app/reports/handler.ts and keep the /reports URL
B. Keep both files and add a rewrite that selects the page or handler from the request's Accept header
C. Move the handler to app/reports/api/route.ts and expose it at /reports/api
D. Export the handler from page.tsx alongside the page's default export

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 an opaque cursor containing both createdAt and the unique order ID
C. Use only the createdAt timestamp of the final returned order
D. Use the total order count followed by the current numeric offset

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 PATCH because all partial updates are inherently idempotent
D. Send POST with an idempotency key stored under a unique constraint

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 "docs" first and ["guides", "install"] second
D. slug is undefined 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. Clone the request before consumption, then read one body as text and the other as JSON
B. Parse the body as JSON first, serialize the resulting object, and assume the serialization always reproduces the exact signed bytes
C. Read request.bodyUsed, reset it to false, and then parse the body again
D. Call request.text() and then call request.json() on the same request

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. Call headers.set("Set-Cookie", ...) twice on one Headers object
B. Join both cookie strings with commas in one Set-Cookie header
C. Return the first cookie in a header and the second cookie in the JSON body
D. Use NextResponse.cookies.set once for each cookie before returning

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. Verify that the action request originated from a React Client Component
C. Accept the ID when it matches a hidden field signed only by client-side JavaScript
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(formData, userId)
B. const action = updateUser.bind(null, userId)
C. const action = updateUser.bind(formData, userId)
D. const action = updateUser.bind(null, formData, userId) so the browser can replace the bound FormData during submission

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. Sanitize database error messages and use them as the primary validation mechanism
B. Validate only a hidden Boolean indicating that client validation succeeded
C. Rely on HTML constraints because invalid forms cannot be submitted by browsers
D. Parse FormData with the schema in the action and return structured field errors

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. Stream bytes to storage while enforcing incremental size and type limits
B. Trust Content-Length completely and buffer the body only when that header claims the file is within the configured limit
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. Retry only the ledger insertion after returning an error
B. Update the balances first and asynchronously reconcile the ledger later
C. Execute all three writes in one database transaction
D. Run all three writes concurrently with Promise.all

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. Rollback only if the current optimistic version matches the failed operation
B. Always restore the value captured before the first request
C. Reload the entire application whenever either request settles
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. A middleware rule that converts every cross-origin PUT request into a same-origin form submission
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. An OPTIONS handler returning the required CORS allow headers

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. 201 Created with the completed export file in the body
B. 204 No Content with a Retry-After request header
C. 304 Not Modified with the identifier of the queued operation
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 If-None-Match with * and return 304 on mismatch
B. Require Last-Modified in the request body and return 202 on mismatch
C. Require Cache-Control: no-store and return 409 for every update
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 204 with a JSON confirmation body
B. Return status 204 with no response body
C. Return status 304 with an empty response body
D. Return status 200 while declaring a nonzero body length but sending no 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. Replace redirect with revalidatePath inside the catch block
B. Catch the redirect and return its error object to the Client Component
C. Run the redirect in finally so it executes after both success and failure
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. Append the canonical comment and leave the temporary entry unchanged
C. Clear every comment and wait for a later full-page cache revalidation
D. Replace the matching temporary entry with the returned canonical comment

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