Skip to content

Scenario-Based Web Development Interview Questions

50 questions with answers. Real-work situations — broken dashboards, flaky tests, unclear requirements — and how a strong junior web developer would handle them.

How to approach these questions

Clarify the situation, list likely causes, say how you would check each one, then give the fix and how you would stop it happening again.

Solved — scenario-basedStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
3 questions free Unlock the rest in seconds
01

An accessibility audit gives your site a low score. What would you fix first?

Save to ▾
Show answer
I would start with issues that block users completely: missing alt text on meaningful images, form inputs without labels, poor colour contrast, and controls that cannot be reached by keyboard. Then I would fix heading order, add a skip link, use semantic landmarks and make focus outlines visible. I would test with Lighthouse or axe, then manually with Tab key navigation and a screen reader like NVDA.
02

A client wants better Google rankings. What HTML-level changes would you make?

Save to ▾
Show answer
I would give every page a unique title and meta description, use exactly one clear h1 with a logical h2 and h3 structure, and add descriptive alt text. I would add canonical tags to avoid duplicate content, structured data such as JSON-LD for courses or FAQs, and internal links with meaningful anchor text. I would also improve Core Web Vitals, since page speed affects ranking.
03

A contact form is receiving hundreds of spam submissions daily. What do you do?

Save to ▾
Show answer
I would layer defences rather than rely on one trick. On the front end, add a hidden honeypot field that bots fill and humans do not, and add an invisible CAPTCHA such as reCAPTCHA v3 or Turnstile. On the server, validate every field, apply rate limiting per IP, reject submissions that arrive too fast after page load, and log patterns. Real protection must be server side because bots skip JavaScript.
04

Product images look blurry on high-resolution phone screens. How do you fix it?

Save to ▾
Show answer
High-density screens have a device pixel ratio of 2 or 3, so a 300 pixel wide image displayed at 300 CSS pixels looks soft. I would export 2x and 3x versions and serve them through srcset with x descriptors or width descriptors plus sizes. For icons and logos I would switch to SVG, which stays sharp at any size and is usually smaller than multiple raster versions.
05

Lighthouse shows a poor Largest Contentful Paint caused by the hero image. What steps do you take?

Save to ▾
Show answer
First I would compress the image and serve it in AVIF or WebP at the correct size using srcset. I would remove loading='lazy' from it, add fetchpriority='high' and a preload link in the head, and make sure it is in the initial HTML rather than injected by JavaScript. I would also serve it from a CDN and check that render-blocking CSS is not delaying the paint.
06

Why should external links opened with target='_blank' use rel='noopener'?

Save to ▾
Show answer
When a page opens a link in a new tab, the new page historically got access to window.opener and could redirect the original tab to a phishing page, an attack called reverse tabnabbing. Adding rel='noopener' removes that reference, and noreferrer also hides the referring URL. Modern browsers apply noopener by default for target='_blank', but adding it explicitly is still good practice for older browsers.
07

Your page shows a horizontal scrollbar on mobile. How do you find and fix the cause?

Save to ▾
Show answer
Horizontal scroll means some element is wider than the viewport. I would open Chrome DevTools device mode and use a temporary rule like * { outline: 1px solid red } to spot the culprit. Common causes are fixed pixel widths, images without max-width: 100%, long unbroken URLs, and 100vw combined with padding. Fixes include max-width, overflow-wrap: anywhere and box-sizing: border-box. I avoid hiding it with overflow-x: hidden without fixing the root cause.
08

A modal appears behind the header even with z-index 9999. What is wrong?

Save to ▾
Show answer
The modal is most likely inside a parent that creates its own stacking context, for example through transform, opacity, filter or a positioned element with a lower z-index. Inside that context the 9999 is compared only with siblings. I would inspect ancestors in DevTools, then either render the modal directly under body, which is what portals do, or remove the property creating the context. The native dialog element with showModal also places it in the top layer.
09

The site's main CSS file is 400 KB and first paint is slow. How do you optimise it?

Save to ▾
Show answer
I would run the Coverage tab in DevTools to measure unused CSS, then remove dead rules with a tool like PurgeCSS. I would extract critical above-the-fold CSS and inline it, loading the rest asynchronously. Splitting styles per page or route, minifying, enabling Brotli compression and caching with long expiry headers also help. Finally I would replace heavy frameworks where only a few components are used.
10

A third-party widget's CSS keeps overriding your button styles. How do you handle it?

Save to ▾
Show answer
First I would check which selector wins in DevTools and why. Options include scoping my styles with a more specific component class, using CSS cascade layers so third-party CSS sits in a lower layer, or loading the widget inside an iframe or Shadow DOM so its styles are isolated. I would avoid adding !important everywhere, because it starts an override war that becomes impossible to maintain.
11

Uploaded images overflow their containers and break the layout. What is the fix?

Save to ▾
Show answer
Images keep their natural size by default, so a 2000 pixel photo will overflow a 350 pixel card. A global rule img { max-width: 100%; height: auto; display: block; } makes them shrink to fit while keeping the aspect ratio. For fixed-size thumbnails I would add width, height and object-fit: cover so different photo shapes crop neatly without stretching.
12

Your page has a high Cumulative Layout Shift because of fonts and ads. How do you reduce it?

Save to ▾
Show answer
For fonts I would preload the main font file, use font-display: swap or optional, and tune fallback fonts with size-adjust so the swap does not move text. For ads and embeds I would reserve space with a fixed min-height or aspect-ratio box before they load. I would also set width and height on all images and avoid inserting banners above existing content after load.
13

An API is being called twice when the page loads. How do you debug it?

Save to ▾
Show answer
I would open the Network tab and check the Initiator column to see which code triggered each request. Common causes are the script being included twice, an event listener attached twice, a function called on both DOMContentLoaded and load, or a framework's development mode running effects twice. I would add a breakpoint or console.trace inside the fetch function, fix the root cause, and add a guard flag only if truly needed.
14

A dashboard page becomes slower the longer it stays open. What could cause it?

Save to ▾
Show answer
This points to a memory leak. Typical causes are setInterval timers never cleared, event listeners added repeatedly on re-render, detached DOM nodes still referenced in arrays, and growing caches. I would take heap snapshots in the DevTools Memory tab a few minutes apart and compare retained objects. Fixes include clearInterval on cleanup, removeEventListener or AbortController for listeners, and limiting cached data size.
15

A cart total shows 0.30000000000000004 instead of 0.3. Why, and how do you fix it?

Save to ▾
Show answer
JavaScript numbers are IEEE 754 floating point, so decimals like 0.1 and 0.2 cannot be stored exactly. For money, I would store and calculate amounts in the smallest unit, such as paise as integers, and convert only for display using Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR' }). The server should always recalculate the final amount, because client-side totals cannot be trusted for payment.
16

Your code throws 'Unexpected token < in JSON' after an API call. What does it mean?

Save to ▾
Show answer
It means response.json() received HTML instead of JSON, usually an error page, a login redirect, or a 404 page from the server. I would check the response status and body in the Network tab, verify the endpoint URL and method, and confirm the server sets Content-Type: application/json. In code I would check response.ok before parsing so users see a clear error instead of a crash.
17

Click handlers do not work on buttons added after the page loads. Why?

Save to ▾
Show answer
The listeners were attached with querySelectorAll when the page loaded, so they exist only on the buttons that were present at that moment. New buttons have no listener. The clean fix is event delegation: attach one listener to a stable parent and check event.target.closest('.btn'). Alternatively, attach the listener when creating each new element, but delegation scales better for large lists.
18

The page stutters while scrolling because of a scroll event handler. How do you fix it?

Save to ▾
Show answer
Scroll events fire many times per second, so heavy work in the handler blocks the main thread. I would throttle the handler or batch DOM writes inside requestAnimationFrame, mark listeners as { passive: true }, and avoid reading layout properties like offsetTop after writing styles. For tasks like lazy loading, sticky effects or reveal animations, I would replace the handler with IntersectionObserver or CSS position: sticky.
19

A comment section displays user input using innerHTML. What is the risk and fix?

Save to ▾
Show answer
It allows stored cross-site scripting: a user can post <img src=x onerror=...> and the script runs for every visitor, stealing sessions or defacing the page. I would switch to textContent or createElement for rendering, escape output on the server, and if rich text is needed, sanitise with a library like DOMPurify. A strict Content Security Policy adds another layer by blocking inline scripts.
20

Users click the Pay button twice and get charged twice. How do you prevent it?

Save to ▾
Show answer
On the front end, I would disable the button and show a loading state as soon as the first click is handled, and re-enable it only on error. But the real fix must be on the server: generate an idempotency key or order id per checkout, and reject or ignore a second request with the same key. Payment gateways support idempotent requests for exactly this reason.
21

Rendering a table with 5,000 rows freezes the browser. What are your options?

Save to ▾
Show answer
Creating thousands of nodes at once blocks the main thread. Options are server-side pagination, rendering in chunks with requestAnimationFrame, or virtual scrolling where only the 30 to 50 visible rows exist in the DOM at any time. I would also build rows in a DocumentFragment, avoid layout reads inside loops, and use CSS content-visibility: auto so off-screen rows skip rendering work.
22

Users lose a long form's data when they accidentally refresh. How do you solve it?

Save to ▾
Show answer
I would autosave the form into sessionStorage or localStorage on input with a small debounce, then restore values on page load and clear them after successful submission. A beforeunload warning can ask users to confirm leaving when there are unsaved changes. Sensitive fields like passwords or card details must never be saved. For multi-step forms, saving drafts on the server is more reliable.
23

A PHP page shows a blank white screen. How do you debug it?

Save to ▾
Show answer
A white screen usually means a fatal error with display_errors turned off. I would check the PHP error log or server log first, for example the Apache or PHP-FPM log. On a local or staging machine I would enable error_reporting(E_ALL) and display_errors. Common causes are syntax errors, missing extensions like pdo_mysql, memory limit exhaustion, or a missing vendor folder. On production, errors should be logged, never displayed.
24

Users get logged out immediately after login when redirected. What could be wrong?

Save to ▾
Show answer
Likely causes are session_start() missing on the next page, output sent before session_start so headers fail, or the session cookie being dropped. Cookie issues include a Secure flag on an HTTP site, a domain mismatch between www and non-www, or SameSite settings during cross-site redirects. I would check the Set-Cookie header in DevTools, verify session.save_path is writable, and redirect to a single canonical domain.
25

A PHP page takes 8 seconds to load. How do you find the bottleneck?

Save to ▾
Show answer
I would measure before guessing, using a profiler like Xdebug or Blackfire, or simple microtime logs around sections. Usually the cause is database queries, such as an N+1 pattern running a query inside a loop, missing indexes, or slow external API calls. Fixes include joining or eager loading, adding indexes, caching results in Redis, making API calls async with a queue, and enabling OPcache.
26

You must upgrade an old project from PHP 7.4 to PHP 8.3. How do you plan it?

Save to ▾
Show answer
I would first set up a staging copy and run a static analyser like PHPStan or Rector with PHP 8 rules to list incompatible code, such as removed functions, changed string comparisons and stricter type errors. Then I would update Composer dependencies to versions supporting PHP 8.3, fix deprecations, run the test suite and manual checks, and deploy with a rollback plan. PHP 7.4 has been unsupported since 2022.
27

You see 'Headers already sent' warnings. What causes it and how do you fix it?

Save to ▾
Show answer
header(), setcookie() and session_start() must run before any output reaches the browser. The warning appears when something was printed earlier, such as an echo, HTML outside PHP tags, whitespace after a closing ?> tag, or a UTF-8 BOM at the start of a file. The message names the file and line that produced output. Removing closing ?> tags in pure PHP files prevents most cases.
28

A search query on a 2 million row products table takes 6 seconds. How do you speed it up?

Save to ▾
Show answer
I would run EXPLAIN to see if it does a full table scan. If the WHERE uses LIKE '%phone%', a normal index cannot help, so I would add a FULLTEXT index with MATCH AGAINST or use a search engine like Elasticsearch or Meilisearch. For filters such as category and price, a composite index in the right order helps. I would also select only needed columns and cache popular searches.
29

Your application logs show frequent deadlock errors. What do you do?

Save to ▾
Show answer
A deadlock happens when two transactions each hold a lock the other needs; InnoDB kills one. I would read SHOW ENGINE INNODB STATUS to see the conflicting queries. Fixes include accessing tables and rows in a consistent order, keeping transactions short, adding indexes so updates lock fewer rows, and avoiding user interaction inside a transaction. The application should also retry the failed transaction once or twice.
30

Pagination becomes very slow on later pages. Why, and how do you fix it?

Save to ▾
Show answer
LIMIT 20 OFFSET 100000 forces MySQL to read and discard 100,000 rows before returning 20, so deep pages get slower. Keyset or cursor pagination fixes this: remember the last seen id and query WHERE id < :last_id ORDER BY id DESC LIMIT 20, which uses the index directly. It suits infinite scroll and APIs. For numbered pages, limiting maximum depth or caching counts also helps.
31

Someone accidentally ran DELETE without a WHERE clause on production. How do you recover?

Save to ▾
Show answer
First I would stop writes to that table to avoid further damage and inform the team. Then I would restore the latest backup to a separate server and, if binary logging is enabled, replay binlog events up to just before the bad statement using mysqlbinlog for point-in-time recovery. Finally I would copy the recovered rows back. Afterwards I would enable safe-updates mode and restrict production access.
32

The database server is overloaded by read traffic. What architecture changes would you suggest?

Save to ▾
Show answer
I would first add caching for frequent reads with Redis or application-level caching. Then I would set up one or more read replicas and route SELECT queries to them while writes go to the primary, keeping replication lag in mind for read-after-write cases. Optimising slow queries and indexes often gives the cheapest wins. Managed services like Amazon RDS make adding replicas straightforward.
33

A client's WordPress site has been hacked and shows spam links. What steps do you take?

Save to ▾
Show answer
I would take a full backup for evidence, put the site in maintenance mode and change all passwords, including hosting, database, FTP and admin users. Then I would compare core files with fresh copies, scan themes, plugins and uploads for injected PHP, remove unknown admin users and check the database for spam content. After cleaning I would update everything, remove unused plugins, add a firewall and request a Google review.
34

Database credentials were accidentally pushed to a public GitHub repository. What now?

Save to ▾
Show answer
Deleting the commit is not enough, because bots scan GitHub within minutes. I would immediately rotate the password and any other exposed keys, check database logs for suspicious access, and then purge the secret from history using git filter-repo. Going forward, secrets belong in environment variables or a secrets manager, .env files go in .gitignore, and secret-scanning tools run in CI.
35

A user can view another user's invoice by changing the id in the URL. What is this and how do you fix it?

Save to ▾
Show answer
This is an Insecure Direct Object Reference, a form of broken access control, the top OWASP risk. The fix is an authorisation check on every request: fetch the invoice with WHERE id = ? AND user_id = ? using the logged-in user's id from the session, and return 404 if not found. Using random UUIDs makes guessing harder but is not a replacement for authorisation checks.
36

An attacker uploaded a PHP web shell through the profile picture feature. How did it happen and how do you prevent it?

Save to ▾
Show answer
The upload likely trusted the file extension or the browser-sent MIME type and saved files inside a web-accessible folder where PHP executes. To prevent it, verify the real type with finfo, re-encode images with GD or Imagick, rename files randomly with safe extensions, store uploads outside the web root or on object storage, and disable PHP execution in the uploads directory through server configuration.
37

After moving to HTTPS, browsers show mixed content warnings. How do you fix them?

Save to ▾
Show answer
Mixed content means an HTTPS page still loads images, scripts or styles over plain HTTP, and browsers block or upgrade them. I would find them in the DevTools console, update hard-coded http:// URLs in templates and the database to https:// or relative paths, and fix third-party embeds. Adding the CSP directive upgrade-insecure-requests is a safety net, and HSTS ensures future visits always use HTTPS.
38

Your frontend on one domain gets a CORS error calling your API on another. How do you resolve it?

Save to ▾
Show answer
The fix belongs on the API server, not the frontend. I would configure it to return Access-Control-Allow-Origin with the exact frontend origin, handle OPTIONS preflight requests with the allowed methods and headers, and add Access-Control-Allow-Credentials: true if cookies are needed. Alternatively, serving the API under the same domain through a reverse proxy, like /api, removes cross-origin calls altogether.
39

Design a secure forgot-password flow.

Save to ▾
Show answer
Show the same message whether or not the email exists to avoid account enumeration. Generate a long random token with random_bytes, store only its hash with a short expiry such as 30 minutes, and email a one-time link. On reset, verify the hash and expiry, set the new password with password_hash, delete the token and invalidate existing sessions. Rate-limit the request endpoint to prevent email flooding.
40

Before launching a new web application, how would you run a basic security review?

Save to ▾
Show answer
I would walk through the OWASP Top 10: access control on every route, injection, authentication, session settings, misconfiguration and outdated components. I would run automated scanners like OWASP ZAP, check dependencies with composer audit and npm audit, verify HTTPS and security headers, and confirm error pages do not leak stack traces. Finally, I would test key flows manually as a normal user trying to access admin pages.
41

Users report being redirected to a gambling site from your pages. What do you check?

Save to ▾
Show answer
This often comes from injected JavaScript or a compromised third-party script. I would check the page source and Network tab for unfamiliar scripts, inspect .htaccess for malicious rewrite rules, search the database and theme files for obfuscated code like base64_decode or eval, and review recently changed files on the server. A strict CSP and Subresource Integrity on CDN scripts help prevent repeat incidents.
42

Your site suddenly shows 502 Bad Gateway. How do you troubleshoot it?

Save to ▾
Show answer
502 means Nginx could not get a valid response from the upstream, usually PHP-FPM or an application server. I would check if the service is running with systemctl status php8.3-fpm, read the Nginx error log and the PHP-FPM log, and confirm the socket path in the config matches. Common causes are crashed workers, exhausted pm.max_children, memory limits or a recent config change. Restarting brings it back, but the root cause must be fixed.
43

You changed DNS to a new server but some users still see the old site. Why?

Save to ▾
Show answer
DNS resolvers and browsers cache records for the TTL period, so changes propagate gradually; with a high TTL like 24 hours, some users keep the old IP for a day. I would check with dig or an online DNS checker from several locations. Best practice is lowering the TTL to 300 seconds a day before migration, keeping the old server running until traffic drains, and then raising the TTL again.
44

A results website expects ten times normal traffic on announcement day. How do you prepare?

Save to ▾
Show answer
I would load test with tools like k6 or JMeter to find the breaking point, then cache result pages aggressively using a CDN and Redis. The database should have proper indexes, and read-heavy queries could go to replicas. On cloud, I would configure auto-scaling and pre-warm extra instances before the announcement. A lightweight static fallback page and a queue for heavy tasks keep the site responsive under peak load.
45

How would you deploy updates without any downtime?

Save to ▾
Show answer
I would use atomic releases: upload the new version into a fresh release folder, install dependencies and build assets there, then switch a current symlink in one step and reload PHP-FPM. Database migrations must be backward compatible, such as adding columns before code uses them, so old and new code both work during the switch. With multiple servers, rolling or blue-green deployment behind a load balancer achieves the same.
46

The server's disk is full and the site has stopped saving data. What do you do?

Save to ▾
Show answer
I would check usage with df -h and find large folders using du -sh /var/* | sort -h. Usual culprits are huge log files, old backups, cached uploads or MySQL binary logs. I would safely clear or compress logs, purge old binlogs with PURGE BINARY LOGS, and move backups off the server. To prevent repeats, set up logrotate, backup retention and disk usage alerts at about 80 percent.
47

A client wants to move a growing site from shared hosting to a VPS. How do you plan the migration?

Save to ▾
Show answer
I would set up the VPS with Nginx, PHP-FPM, MySQL, firewall and SSL, matching PHP versions and extensions. Then I would copy files with rsync, export and import the database, and test the site using a hosts file entry before touching DNS. After lowering the TTL, I would do a final data sync during low traffic, switch DNS, monitor logs, and keep the old hosting live for a few days as fallback.
48

Emails sent from your website contact form land in spam. How do you fix it?

Save to ▾
Show answer
I would stop sending through PHP mail() from the web server and use an authenticated SMTP or transactional email service. Then I would publish SPF to authorise the sender, DKIM to sign messages, and a DMARC policy in DNS. The From address should belong to the verified domain, while the visitor's email goes in Reply-To. Mail testing tools show the spam score and missing records.
49

Time to first byte is over 2 seconds even for simple pages. What do you check?

Save to ▾
Show answer
High TTFB points to the server, not the browser. I would check if OPcache is enabled, profile slow database queries, look for blocking external API calls during page generation, and check whether the server is low on CPU or memory. Fixes include full-page caching for anonymous users, object caching with Redis, upgrading PHP, choosing a server region close to Indian users, and putting a CDN in front.
50

How do you manage configuration and secrets across local, staging and production?

Save to ▾
Show answer
I keep code identical across environments and change only configuration through environment variables, usually loaded from a .env file that is never committed. A .env.example documents required keys without values. In production, secrets live in the server environment, the CI secret store or a cloud secrets manager. Each environment has separate database credentials and API keys, so a staging leak cannot affect production.

Frequently asked questions

Why are scenario-based questions important?

They show how you think on real problems. Interviewers use them to separate people who memorised definitions from people who have done the work.

How should I answer them?

Clarify the situation, list likely causes, say how you would check each one, then give the fix and how you would stop it happening again.