# Frontend Developer roadmap

> Build fast, accessible, production-grade web interfaces with HTML, CSS, JavaScript, TypeScript and React.

Canonical: https://www.internhack.in/roadmaps/tracks/frontend
Last updated: 2026-11-28

20 sections, 93 topics, about 389 hours.

A complete path from how the web delivers a page to shipping a production React application. You start with the internet, HTTP and the browser, master semantic HTML and modern CSS layout, then go deep on JavaScript and TypeScript. From there you pick a UI framework (React recommended), learn its rendering model, routing, state, data fetching and forms, and harden your work with testing, accessibility, performance and security practices. The track finishes with meta-frameworks like Next.js, browser APIs and PWAs, design systems, deployment and a capstone project you can show employers.

## Outcomes

- Explain how browsers fetch, parse and render a page, and use that knowledge to debug and optimise
- Build responsive, accessible layouts with semantic HTML and modern CSS
- Write idiomatic JavaScript and strictly typed TypeScript, including async code and DOM work
- Build and structure React applications with routing, state management, data fetching and validated forms
- Test frontends with unit, component and end-to-end tests
- Meet WCAG accessibility, Core Web Vitals and frontend security expectations
- Ship a Next.js or Vite app to production with CI, environment config and monitoring

## Prerequisites

- Comfortable using a computer, a code editor and a terminal
- No prior programming experience required

## How the Web Delivers a Page

The journey from typing a URL to pixels on screen: networks, names, requests and the browser engine.

### How the Internet Works

core · beginner · about 3 h · https://www.internhack.in/roadmaps/tracks/frontend/internet

Understand packets, IP addresses, routers, clients and servers so the rest of web development has a mental model to hang on.

The internet is a network of networks. Your laptop, a phone tower, a data centre in another country: all of them agree to speak the same protocols, so data can hop between them without anyone owning the whole path.

#### The core ideas
- **IP addresses** identify machines. IPv4 looks like `93.184.216.34`; IPv6 is longer and exists because we ran out of IPv4 addresses.
- **Packets** are small chunks of data. A web page is split into many packets that may take different routes and get reassembled at the other end.
- **TCP** guarantees ordered, complete delivery (it retransmits lost packets). **UDP** is faster but fire-and-forget, which suits video calls and games. HTTP/3 runs over **QUIC**, which is built on UDP.
- **Ports** let one machine run many services: 443 for HTTPS, 80 for HTTP, 5173 for your local Vite dev server.
- **Clients and servers**: the browser is a client that asks; a server is a program that listens and answers.

#### Why a frontend developer cares
Latency (how long a round trip takes) often matters more than bandwidth. Every extra request to a far-away server costs tens or hundreds of milliseconds, which is why CDNs, caching and bundling exist. When a page is "slow" you need to know whether the network, the server or your JavaScript is to blame.

#### Good enough to move on
You can explain, in plain words, what happens between a click and a response: the name is resolved to an IP, a TCP (or QUIC) connection is opened, TLS encrypts it, a request is sent and a response streams back. You do not need to memorise the OSI model layer by layer.

Key concepts: IP addresses (IPv4 and IPv6), Packets and routing, TCP vs UDP, Ports and sockets, Client-server model, Latency vs bandwidth, QUIC and HTTP/3 transport.

Mini project: Run traceroute (tracert on Windows) and ping against three sites on different continents, then write a short note explaining the hop counts and latency differences you observed.

Self-check: Why does a site hosted on another continent feel slower even when your connection has plenty of bandwidth?

Resources:
- [How does the Internet work?](https://developer.mozilla.org/en-US/docs/Learn_web_development/Howto/Web_mechanics/How_does_the_Internet_work) (MDN)
- [Cloudflare Learning Center](https://www.cloudflare.com/learning/) (Cloudflare)

### DNS and Domain Names

core · beginner · about 2 h · https://www.internhack.in/roadmaps/tracks/frontend/dns

Learn how human-friendly domain names are translated into IP addresses and which DNS records you will touch when deploying a site.

The **Domain Name System** is the internet's phone book. Browsers cannot connect to `example.com` directly; they need an IP address, and DNS provides it.

#### How a lookup works
1. The browser checks its own cache, then the operating system cache.
2. If nothing is cached, a **recursive resolver** (often run by your ISP, or public ones like 1.1.1.1 or 8.8.8.8) does the legwork.
3. The resolver asks a **root server**, which points to the **TLD server** for `.com`, which points to the domain's **authoritative nameserver**, which finally returns the record.
4. The answer is cached for as long as its **TTL** (time to live) allows.

#### Records you will actually use
- **A / AAAA**: name to IPv4 / IPv6 address.
- **CNAME**: an alias pointing to another name (common when a host like Vercel or Netlify gives you a target).
- **TXT**: arbitrary text, used for domain verification and email security (SPF, DKIM).
- **MX**: where email for the domain goes.
- **NS**: which nameservers are authoritative.

#### Pitfalls
- Changing a record does not take effect instantly for everyone: old answers live on until their TTL expires. Lower the TTL before a planned migration.
- A root (apex) domain like `example.com` usually cannot be a CNAME; hosts offer ALIAS/ANAME records or specific A records instead.

You are ready to move on when you can point a custom domain at a hosted frontend and debug it with `nslookup` or `dig`.

Key concepts: Resolvers, root, TLD and authoritative servers, A and AAAA records, CNAME and apex domains, TTL and caching, TXT, MX and NS records, dig and nslookup, DNS over HTTPS.

Mini project: Use dig or nslookup to inspect the A, CNAME, MX and TXT records of three well-known sites, and document which hosting or email providers they appear to use.

Self-check: You changed an A record ten minutes ago but some users still hit the old server. What is the most likely reason?

Resources:
- [What is DNS?](https://www.cloudflare.com/learning/dns/what-is-dns/) (Cloudflare)
- [What is a domain name?](https://developer.mozilla.org/en-US/docs/Learn_web_development/Howto/Web_mechanics/What_is_a_domain_name) (MDN)

### HTTP and HTTPS

core · beginner · about 4 h · https://www.internhack.in/roadmaps/tracks/frontend/http

The request/response protocol every web page and API call uses: methods, status codes, headers, caching and TLS.

**HTTP** is a text-based conversation between a client and a server. The client sends a request (method, path, headers, optional body) and the server replies with a status code, headers and a body. Almost everything you build on the frontend ends up as HTTP traffic, so reading it fluently is a superpower.

#### The pieces
- **Methods**: `GET` (read, no body, safe to repeat), `POST` (create or trigger), `PUT`/`PATCH` (replace/update), `DELETE`. `OPTIONS` shows up in CORS preflights.
- **Status codes**: 2xx success (200, 201, 204), 3xx redirects (301, 302, 304 Not Modified), 4xx client errors (400, 401, 403, 404, 429), 5xx server errors (500, 502, 503).
- **Headers** carry metadata: `Content-Type`, `Authorization`, `Cookie`/`Set-Cookie`, `Cache-Control`, `ETag`, `Accept-Encoding`.
- **Cookies** are small values the server asks the browser to store and send back automatically, which is how sessions work.

#### HTTPS and versions
HTTPS is HTTP inside a **TLS** encrypted connection. Certificates prove the server owns the domain. Modern browsers block many features (service workers, geolocation, clipboard) on plain HTTP except on localhost. HTTP/1.1 opens several connections; **HTTP/2** multiplexes many requests over one; **HTTP/3** uses QUIC for faster setup on flaky networks.

#### Caching basics
`Cache-Control: max-age=31536000, immutable` tells the browser a file never changes (perfect for hashed build assets). `no-cache` means "revalidate before use", and `ETag` lets the server answer 304 without resending the body.

#### Good enough to move on
Open the DevTools Network tab on any site and explain what each request is, why it got its status code and whether it came from cache.

Key concepts: Request and response anatomy, HTTP methods, Status codes, Headers and content types, Cookies and sessions, HTTPS, TLS and certificates, Cache-Control and ETag, HTTP/2 and HTTP/3, DevTools Network panel.

Mini project: Use curl -v and the DevTools Network panel to fetch a public API; annotate one request and response line by line, including every header and why the status code was returned.

Self-check: What is the difference between a 401 and a 403 response, and between Cache-Control no-cache and no-store?

Resources:
- [HTTP](https://developer.mozilla.org/en-US/docs/Web/HTTP) (MDN)
- [HTTP caching](https://web.dev/articles/http-cache) (web.dev)

### How Browsers Render a Page

core · beginner · about 3 h · https://www.internhack.in/roadmaps/tracks/frontend/browser-rendering

Follow the critical rendering path: parsing HTML and CSS, building the DOM and CSSOM, layout, paint and compositing.

Once bytes arrive, the browser engine (Blink in Chrome and Edge, WebKit in Safari, Gecko in Firefox) turns them into pixels. Knowing this pipeline explains most performance advice you will ever read.

#### The pipeline
1. **Parse HTML** into the **DOM** tree. The parser is streaming, so the page can start rendering before all HTML has arrived.
2. **Parse CSS** into the **CSSOM**. CSS is render-blocking: the browser will not paint until the stylesheets in `<head>` are loaded.
3. **Scripts**: a plain `<script>` pauses HTML parsing while it downloads and runs. `defer` runs after parsing, in order; `async` runs whenever it arrives. Modules (`type="module"`) are deferred by default.
4. **Style and layout**: combine DOM and CSSOM into a render tree, then compute every box's size and position.
5. **Paint** fills in pixels; **composite** stacks layers on the GPU.

#### Why it matters
- Changing `width` or `top` forces layout again (expensive). Changing `transform` or `opacity` usually only needs compositing (cheap), which is why smooth animations use them.
- Reading layout values (`offsetHeight`) right after writing styles forces a synchronous layout, known as **layout thrashing**.
- The JavaScript main thread also handles rendering and input, so long-running scripts make the page feel frozen.

#### Good enough to move on
You can explain why scripts go at the end of `<body>` or use `defer`, why CSS is loaded early, and what "reflow" and "repaint" mean. Record a page load in the DevTools Performance panel once and identify parsing, scripting, layout and paint in the timeline.

Key concepts: DOM and CSSOM construction, Render-blocking resources, script defer, async and module, Layout, paint and composite, Reflow and layout thrashing, Browser engines, DevTools Performance panel.

Mini project: Build a small page with a large stylesheet and a heavy script, record it in the Performance panel, then fix the loading order with defer and measure the difference in first paint.

Self-check: Why is animating transform cheaper than animating left, in terms of the rendering pipeline?

Resources:
- [How browsers work](https://developer.mozilla.org/en-US/docs/Web/Performance/Guides/How_browsers_work) (MDN)
- [Critical rendering path](https://developer.mozilla.org/en-US/docs/Web/Performance/Guides/Critical_rendering_path) (MDN)
- [Chrome DevTools](https://developer.chrome.com/docs/devtools) (Chrome for Developers)

## Writing Meaningful HTML

Structure content with the right elements so it works for browsers, search engines and assistive technology.

### HTML Document Essentials

core · beginner · about 5 h · https://www.internhack.in/roadmaps/tracks/frontend/html-document

Elements, attributes, the document skeleton, text, links, images and tables: the raw material of every page.

HTML describes **what content is**, not how it looks. A browser reads tags like `<h1>`, `<p>` and `<a>` and builds a tree of elements from them.

#### The skeleton
Every page needs `<!doctype html>` (standards mode), an `<html lang="en">` root, a `<head>` with `<meta charset="utf-8">`, the viewport meta tag (`width=device-width, initial-scale=1`) and a `<title>`, then a `<body>` with visible content. Forgetting the viewport tag is the classic reason a site looks tiny on phones.

#### Everyday elements
- Text: headings `<h1>` to `<h6>` (in order, no skipping for styling), `<p>`, `<strong>`, `<em>`, lists `<ul>`/`<ol>`/`<li>`.
- Links: `<a href>` with meaningful text; use `target="_blank"` sparingly.
- Media: `<img src alt width height>` (always set `alt`, and dimensions to avoid layout shift), `<picture>`, `<video>`, `<audio>`.
- Tables for **tabular data only**, with `<th>`, `<thead>`, `<caption>`.

#### Attributes and nesting
Attributes configure elements (`id`, `class`, `href`, `data-*`). Block-level vs inline is now a CSS concern, but invalid nesting (a `<div>` inside a `<p>`) still produces surprising DOM trees because the parser auto-closes tags.

#### Pitfalls
- Using `<br>` or empty paragraphs for spacing (use CSS).
- `<div>` and `<span>` everywhere with no meaning.
- Missing `alt`, or alt text like "image of".

Move on once you can hand-write a multi-section page from memory and it passes the W3C validator with no errors.

Key concepts: Doctype, head and body, Viewport and charset meta tags, Headings, paragraphs and lists, Links and navigation, Images, alt text and media, Tables for data, Global and data-* attributes, HTML validation.

Mini project: Hand-write a personal profile page with a bio, a list of skills, a table of projects and embedded images, then run it through the W3C validator until it reports zero errors.

Self-check: What goes wrong on mobile if you forget the viewport meta tag, and why?

Resources:
- [HTML: HyperText Markup Language](https://developer.mozilla.org/en-US/docs/Web/HTML) (MDN)
- [Learn HTML](https://web.dev/learn/html) (web.dev)
- [W3C Markup Validation Service](https://validator.w3.org/) (W3C)

### Semantic and Accessible HTML

core · beginner · about 4 h · https://www.internhack.in/roadmaps/tracks/frontend/semantic-html

Choose elements for their meaning so pages are navigable by screen readers, keyboards and search engines out of the box.

Semantic HTML means picking the element whose meaning matches the content. A `<button>` is focusable, activates on Enter and Space, and announces itself as a button. A `<div onclick>` does none of that until you rebuild it by hand. Semantics are the cheapest accessibility you will ever get.

#### Landmarks and structure
- `<header>`, `<nav>`, `<main>` (once per page), `<aside>`, `<footer>` create landmarks screen reader users jump between.
- `<article>` is self-contained content; `<section>` is a themed group, ideally with a heading.
- A logical heading outline (one `<h1>`, then `<h2>`s) is how many users skim a page.

#### Accessibility basics baked into HTML
- Every image needs an `alt`: describe the purpose, or use `alt=""` for purely decorative images.
- Links say where they go ("Download the 2024 report", not "click here").
- Buttons do things, links go places. Do not swap them.
- Set `lang` on `<html>` so screen readers use the right pronunciation.
- Associate every form control with a `<label>`.
- Use `<details>`/`<summary>` and `<dialog>` for native disclosure and modal patterns.

#### The first rule of ARIA
If a native element exists, use it instead of adding ARIA roles to a `<div>`. ARIA changes what is announced but adds no behaviour.

#### Good enough to move on
Navigate your own page with only the keyboard (Tab, Shift+Tab, Enter, Space), and use a screen reader's landmark or heading list once (VoiceOver rotor or NVDA elements list). If everything is reachable and makes sense, your semantics are sound.

Key concepts: Landmark elements, article vs section vs div, Heading outline, Meaningful alt text, Buttons vs links, details, summary and dialog, First rule of ARIA, Keyboard-only smoke test.

Mini project: Take a div-soup landing page (write one or find one) and refactor it to semantic HTML with landmarks, a proper heading outline, real buttons and labelled images; verify with a keyboard-only walkthrough.

Self-check: What does a native button give you for free that a div with a click handler does not?

Resources:
- [HTML: A good basis for accessibility](https://developer.mozilla.org/en-US/docs/Learn_web_development/Core/Accessibility/HTML) (MDN)
- [Learn Accessibility](https://web.dev/learn/accessibility) (web.dev)
- [Accessibility Fundamentals](https://www.w3.org/WAI/fundamentals/) (W3C WAI)

### HTML Forms and Native Validation

core · beginner · about 4 h · https://www.internhack.in/roadmaps/tracks/frontend/html-forms

Build forms with the right input types, labels and built-in validation before reaching for any JavaScript library.

Forms are how users talk back to your app: sign-up, search, checkout, settings. The browser already provides a lot of behaviour; learn it first so libraries later feel like enhancements rather than magic.

#### Building blocks
- `<form action method>` wraps controls; submitting sends `name=value` pairs. In SPAs you usually intercept `submit` with JavaScript, but the semantics still matter (Enter submits, password managers work).
- **Input types** such as `email`, `tel`, `url`, `number`, `date`, `checkbox`, `radio`, `file` give mobile users the right keyboard and built-in checks.
- `<select>`, `<textarea>`, `<fieldset>` with `<legend>` for grouped radios or checkboxes.
- Every control needs a visible `<label for>`; placeholders are hints, not labels.

#### Native validation
Attributes like `required`, `minlength`, `maxlength`, `pattern`, `min`, `max` and `type="email"` validate without code. The `:invalid` and `:user-invalid` pseudo-classes let you style errors, and the Constraint Validation API (`checkValidity()`, `setCustomValidity()`) lets JavaScript hook in.

#### UX that respects users
- Use `autocomplete` values (`email`, `current-password`, `one-time-code`, `postal-code`) so autofill works.
- Show errors next to the field, in text, not only in red.
- Never rely on client-side validation for security: the server must validate again.

Move on when you can build an accessible multi-field form (with a radio group and a file input) that validates natively and submits its data to a test endpoint.

Key concepts: form, action and method, Input types, Labels, fieldset and legend, Built-in validation attributes, Constraint Validation API, autocomplete tokens, :invalid and :user-invalid styling.

Mini project: Build a job application form with text, email, phone, a radio group, a resume file upload and a consent checkbox, using only native validation and styled error states.

Self-check: Why is a placeholder not an acceptable replacement for a label?

Resources:
- [Learn Forms](https://web.dev/learn/forms) (web.dev)
- [The form element](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/form) (MDN)

### SEO and Metadata Basics

recommended · beginner · about 2 h · https://www.internhack.in/roadmaps/tracks/frontend/seo-basics

Help search engines and social platforms understand your pages with titles, meta descriptions, structured data and crawlable markup.

Search engine optimisation for developers is mostly about not getting in the way. Good content wins, but broken technical foundations can hide good content completely.

#### What you control in markup
- A unique, descriptive `<title>` and `<meta name="description">` per page.
- One clear `<h1>` and semantic structure; crawlers use headings and landmarks too.
- **Canonical URLs** (`<link rel="canonical">`) to avoid duplicate-content confusion.
- **Open Graph** and Twitter card tags (`og:title`, `og:image`) control link previews in chat apps and social feeds.
- **Structured data** in JSON-LD (schema.org types like `Article`, `Product`, `JobPosting`) can unlock rich results.
- Real `<a href>` links, because crawlers follow hrefs, not click handlers.

#### Site-level concerns
- `robots.txt` and `sitemap.xml` tell crawlers what to fetch.
- Fast, mobile-friendly pages rank better; Core Web Vitals are a ranking signal.
- **Client-side rendering risk**: if content only appears after JavaScript runs, some crawlers and most link-preview bots will see an empty page. This is one of the main reasons server rendering and static generation exist.

#### Good enough to move on
Your pages have correct titles, descriptions, social previews that render when you paste the link into a chat app, and a sitemap. Deeper SEO (keyword research, link building) is marketing work, not a frontend prerequisite.

Key concepts: Title and meta description, Canonical URLs, Open Graph and social cards, Structured data (JSON-LD), robots.txt and sitemaps, Crawlability of client-rendered pages.

Mini project: Add complete metadata, Open Graph tags, a JSON-LD Person or Article block and a sitemap to your profile page, then verify the social preview and run Google's Rich Results Test.

Self-check: Why might a purely client-rendered page show an empty preview when its link is shared?

Resources:
- [SEO Starter Guide](https://developers.google.com/search/docs/fundamentals/seo-starter-guide) (Google Search Central)
- [The Open Graph protocol](https://ogp.me/)

## CSS Foundations and Layout

How styles are chosen and combined, how boxes are sized, and the two layout systems you will use every day.

### Selectors, Specificity and the Cascade

core · beginner · about 4 h · https://www.internhack.in/roadmaps/tracks/frontend/css-cascade

Learn how the browser decides which rule wins when several target the same element, and how to write selectors that stay predictable.

CSS stands for Cascading Style Sheets, and the cascade is the algorithm that resolves conflicts. Most "CSS is broken" moments are really cascade misunderstandings.

#### Selectors
- Type (`p`), class (`.card`), id (`#main`), attribute (`[type="email"]`).
- Combinators: descendant (`.nav a`), child (`>`), sibling (`+`, `~`).
- Pseudo-classes describe state (`:hover`, `:focus-visible`, `:nth-child(2n)`, `:not()`); pseudo-elements create virtual parts (`::before`, `::placeholder`).

#### How a winner is chosen
1. **Origin and importance**: user-agent styles, then yours; `!important` flips priority.
2. **Cascade layers** (`@layer`): earlier layers lose to later ones regardless of specificity.
3. **Specificity**: counted as (ids, classes/attributes/pseudo-classes, types). `#a` beats `.b.c.d`. `:where()` contributes zero; `:is()` takes its most specific argument.
4. **Source order**: if everything else ties, the later rule wins.

**Inheritance** is separate: properties like `color` and `font-family` pass to children, while `margin` and `border` do not. `inherit`, `initial`, `unset` and `revert` let you control it.

#### Habits that scale
- Style mostly with single classes; avoid ids and deep descendant chains.
- Treat `!important` as a smell except in utility layers.
- Use DevTools' Styles pane: it shows crossed-out losing declarations and why.

Move on when you can predict, before refreshing, which of two conflicting rules applies, and explain it using specificity or order.

Key concepts: Basic and attribute selectors, Combinators, Pseudo-classes and pseudo-elements, Specificity calculation, Inheritance and inherit/unset/revert, :is(), :where() and :not(), Cascade layers (@layer), DevTools Styles pane.

Mini project: Create a specificity quiz page: ten pairs of conflicting rules with a hidden answer for each, then verify every answer in DevTools.

Self-check: Which wins and why: .nav .link.active or #header a?

Resources:
- [Learn CSS](https://web.dev/learn/css) (web.dev)
- [Specificity](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_cascade/Specificity) (MDN)
- [CSS reference](https://developer.mozilla.org/en-US/docs/Web/CSS) (MDN)

### Box Model, Units and Typography

core · beginner · about 5 h · https://www.internhack.in/roadmaps/tracks/frontend/box-model

Every element is a box: master sizing, spacing, display types, positioning, units and readable text.

Every element renders as a rectangle made of **content**, **padding**, **border** and **margin**. Layout bugs usually come from misunderstanding one of those four layers.

#### Sizing and display
- By default `width` sets the content box, so padding and border make the element wider than you asked. Almost every project sets `*, *::before, *::after { box-sizing: border-box; }`.
- `display: block` fills the line; `inline` flows with text and ignores width/height; `inline-block` flows but respects sizing; `none` removes it.
- Vertical margins between blocks **collapse** (the larger one wins), which surprises everyone once.
- `overflow` decides what happens when content does not fit.

#### Positioning
`static` (default), `relative` (offset from itself, creates a positioning context), `absolute` (relative to the nearest positioned ancestor), `fixed` (relative to the viewport), `sticky` (switches between relative and fixed). `z-index` only works inside **stacking contexts**, which are created by positioning, `opacity < 1`, `transform` and others.

#### Units
- `px` for hairlines and borders; `rem` for type and spacing (respects user font settings); `em` relative to the current font; `%` relative to the parent; `vw`/`vh` and the newer `dvh`/`svh` for viewport sizes; `ch` for line lengths.
- `clamp(1rem, 2.5vw, 1.5rem)` gives fluid sizes with limits.

#### Typography and colour
Set a readable base size (around 16px), line-height near 1.5, line length of 45 to 75 characters, and load web fonts with `font-display: swap`. Check text contrast (4.5:1 for body text).

Move on when you can build a card component from scratch and explain every pixel of its size in DevTools' box model diagram.

Key concepts: Content, padding, border, margin, box-sizing: border-box, display types, Margin collapsing, position and stacking contexts, rem, em, %, vw and dvh, clamp(), min() and max(), Web fonts and font-display, Color formats and contrast.

Mini project: Build a pricing card and a sticky header with a dropdown, using rem-based spacing, a web font and fluid headings with clamp(); make sure the dropdown layers correctly above page content.

Self-check: You set z-index: 9999 on a dropdown but it still appears behind another element. What are two possible causes?

Resources:
- [The box model](https://developer.mozilla.org/en-US/docs/Learn_web_development/Core/Styling_basics/Box_model) (MDN)
- [Learn CSS: Box Model](https://web.dev/learn/css/box-model) (web.dev)

### Flexbox

core · beginner · about 4 h · https://www.internhack.in/roadmaps/tracks/frontend/flexbox

One-dimensional layout for rows or columns: alignment, spacing, growing and shrinking items.

Flexbox lays items out along **one axis** at a time. It is the default tool for navbars, toolbars, centering, card rows and any component whose children line up.

#### Mental model
Set `display: flex` on a container and its direct children become flex items. The **main axis** follows `flex-direction` (row by default); the **cross axis** is perpendicular.
- `justify-content` distributes items along the main axis (`space-between`, `center`).
- `align-items` aligns them on the cross axis (`center`, `stretch`, `baseline`).
- `gap` adds space between items; prefer it over margins.
- `flex-wrap: wrap` lets items flow onto new lines.

#### Sizing items
`flex: 1` is shorthand for grow 1, shrink 1, basis 0: items share free space equally. `flex: 0 0 200px` fixes a width. `flex-shrink: 0` stops an icon from being squashed. A common bug is text refusing to truncate inside a flex item; the fix is `min-width: 0` because flex items default to `min-width: auto`.

#### When not to use it
If you are trying to line things up in both rows and columns at once (a real grid, a page layout with sidebars), reach for CSS Grid. Flexbox and Grid are partners, not rivals.

Move on when you can build a responsive navbar, a vertically centred hero and a row of equal-height cards without looking anything up.

Key concepts: Main axis and cross axis, justify-content and align-items, gap, flex-grow, flex-shrink, flex-basis, flex-wrap, align-self and order, min-width: 0 truncation fix.

Mini project: Build a responsive app header with a logo, a search bar that grows to fill space, and action icons that never shrink, plus a wrapping tag list below it.

Self-check: What does flex: 1 actually expand to, and why do long words sometimes overflow a flex item?

Resources:
- [A Complete Guide to Flexbox](https://css-tricks.com/snippets/css/a-guide-to-flexbox/) (CSS-Tricks)
- [Flexbox](https://developer.mozilla.org/en-US/docs/Learn_web_development/Core/CSS_layout/Flexbox) (MDN)
- [Flexbox Froggy](https://flexboxfroggy.com/)

### CSS Grid

core · beginner · about 5 h · https://www.internhack.in/roadmaps/tracks/frontend/css-grid

Two-dimensional layout with rows and columns: page shells, galleries, dashboards and complex alignment.

CSS Grid controls rows **and** columns together. Where flexbox lets content decide its size, grid lets the container define a structure that content slots into.

#### Core syntax
- `display: grid` plus `grid-template-columns: 200px 1fr` gives a sidebar layout. The `fr` unit divides remaining space.
- `repeat(auto-fill, minmax(220px, 1fr))` creates a responsive gallery with **no media queries**: as many columns as fit, each at least 220px.
- Place items with line numbers (`grid-column: 1 / -1` spans everything) or with named **template areas**, which read like an ASCII map of the layout.
- `gap`, `place-items` and `place-content` handle spacing and alignment.

#### Useful details
- `auto-fill` keeps empty tracks; `auto-fit` collapses them so items stretch.
- Implicit rows are created automatically; `grid-auto-rows` sizes them.
- **Subgrid** (`grid-template-columns: subgrid`) lets nested components align to the parent grid, which fixes the classic "card footers do not line up" problem.
- Visual order changes (placing items out of source order) do not change keyboard or screen reader order, so keep the DOM order logical.

#### Grid or flexbox?
Rule of thumb: layout of the **page or section** is grid; alignment **inside a component** is often flexbox. Plenty of components use both.

Move on when you can build a holy-grail layout (header, sidebar, main, footer) with template areas and a responsive image gallery with minmax.

Key concepts: Grid tracks and the fr unit, repeat(), minmax() and auto-fill/auto-fit, Line-based placement, Named template areas, Implicit grid and auto rows, Subgrid, Source order and accessibility.

Mini project: Build a dashboard shell with named areas (header, sidebar, main, footer) that rearranges on mobile, and a stats card grid inside main that auto-fits without media queries.

Self-check: What is the practical difference between auto-fill and auto-fit when there are only two items?

Resources:
- [A Complete Guide to CSS Grid](https://css-tricks.com/snippets/css/complete-guide-grid/) (CSS-Tricks)
- [CSS grid layout](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_grid_layout) (MDN)
- [Grid Garden](https://cssgridgarden.com/)

## Responsive and Modern CSS

Make layouts adapt to any screen, keep styles themeable and use the newest platform features with confidence.

### Responsive Design

core · beginner · about 5 h · https://www.internhack.in/roadmaps/tracks/frontend/responsive-design

Build layouts that work from small phones to wide monitors using fluid sizing, media queries and responsive images.

Responsive design means one codebase that adapts to any screen, input method and user preference. Most traffic to consumer sites is mobile, so this is not optional.

#### Principles
- **Mobile first**: write base styles for small screens, then add `@media (min-width: 48rem)` rules as space grows. It keeps CSS simpler than overriding desktop styles downward.
- **Fluid over fixed**: percentages, `fr`, `minmax()` and `clamp()` reduce the number of breakpoints you need.
- Choose breakpoints where **your content breaks**, not at specific device widths.
- Tap targets should be at least about 44px; hover is not available on touch devices, so never hide essential actions behind it (`@media (hover: hover)` helps).

#### Responsive media
- `img { max-width: 100%; height: auto; }` stops overflow.
- `srcset` and `sizes` let the browser download the right resolution; `<picture>` swaps formats or art direction.

#### User preference queries
- `prefers-color-scheme` for dark mode.
- `prefers-reduced-motion` to tone down animation for people with vestibular disorders.
- `prefers-contrast` for higher contrast.

#### Testing
Use DevTools device mode, but also test on a real phone: viewport height with browser chrome (`100vh` vs `100dvh`), virtual keyboards and touch behaviour differ from emulation.

Move on when a page you built has no horizontal scroll at 320px wide, reads well at 1440px, and respects dark mode and reduced motion.

Key concepts: Mobile-first media queries, Content-driven breakpoints, Fluid layouts and clamp(), Responsive images with srcset and sizes, prefers-color-scheme and dark mode, prefers-reduced-motion, Touch targets and hover media, Device mode and real-device testing.

Mini project: Build a responsive blog article page with a collapsible nav, fluid typography, a responsive hero image using srcset, and a dark theme driven by prefers-color-scheme.

Self-check: Why is mobile-first CSS usually shorter than desktop-first CSS?

Resources:
- [Learn Responsive Design](https://web.dev/learn/design) (web.dev)
- [Responsive web design](https://developer.mozilla.org/en-US/docs/Learn_web_development/Core/CSS_layout/Responsive_Design) (MDN)

### Custom Properties and Modern CSS Features

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/frontend/modern-css

CSS variables, container queries, :has(), nesting, cascade layers and other features that replaced many preprocessor and JavaScript tricks.

CSS has changed more in the last few years than in the decade before. Many things that used to need Sass or JavaScript are now native.

#### Custom properties (CSS variables)
`--brand: oklch(60% 0.2 250);` defined on `:root` and used as `color: var(--brand)`. Unlike Sass variables they are **live**: they cascade, inherit, can change inside media queries or on a class, and JavaScript can update them. This is the foundation of theming and dark mode (swap a handful of tokens, not every rule). Provide fallbacks with `var(--x, 1rem)`.

#### Container queries
`container-type: inline-size` on a wrapper, then `@container (min-width: 400px) { ... }` styles a component based on **its own available space** rather than the viewport. A card can be compact in a sidebar and wide in the main column with the same CSS.

#### Relational and structural selectors
- `:has()` is the long-awaited parent selector: `.card:has(img)`, or `form:has(:invalid)` to style a form that contains errors.
- Native **nesting** (`.card { & h2 { ... } }`) now works in all modern browsers.
- `@layer` organises resets, base, components and utilities so specificity fights disappear.

#### Also worth knowing
Logical properties (`margin-inline`, `padding-block`) for right-to-left support, `aspect-ratio`, `accent-color`, `color-mix()`, the `oklch()` colour space, `@supports` for feature detection, and scroll-driven animations and view transitions for newer projects.

#### Pitfall
Check support on caniuse or MDN's compatibility tables before depending on the very newest features, and design so the page still works if a feature is missing.

Move on when you can build a themeable component with custom properties that also adapts with a container query.

Key concepts: Custom properties and theming, Container queries, :has() relational selector, Native CSS nesting, Cascade layers, Logical properties, aspect-ratio, color-mix() and oklch(), @supports and progressive enhancement, View transitions and scroll-driven animations.

Mini project: Build a product card that switches between stacked and horizontal layouts via a container query, supports light, dark and a brand theme through custom properties, and highlights itself with :has() when its checkbox is selected.

Self-check: How is a CSS custom property fundamentally different from a Sass variable?

Resources:
- [Using CSS custom properties](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties) (MDN)
- [CSS container queries](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_containment/Container_queries) (MDN)
- [Can I use](https://caniuse.com/)

### Transitions and CSS Animations

recommended · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/frontend/css-motion

Add motion that communicates state changes using transitions, keyframes and transforms, while staying fast and respectful of user preferences.

Motion helps users understand what changed: a menu slides from the button that opened it, a toast fades in, a loading state pulses. Bad motion is slow, janky or nauseating.

#### Transitions
`transition: transform 200ms ease-out, opacity 200ms;` animates between two states when a property changes (on hover, focus or a class toggle). Keep UI transitions short: roughly 150 to 300ms.

#### Keyframe animations
`@keyframes` define multi-step sequences, applied with `animation: spin 1s linear infinite`. Use them for loaders, attention cues and entrance effects. `animation-fill-mode` controls what happens before and after.

#### Transforms and performance
`transform` (translate, scale, rotate) and `opacity` can be animated on the compositor without layout or paint, so they stay smooth at 60fps. Animating `width`, `height`, `top` or `box-shadow` triggers layout or paint on every frame. `will-change` is a hint for the browser; use it sparingly.

#### Easing and accessibility
- `ease-out` feels responsive for things entering; `ease-in` suits exits. `cubic-bezier()` and the newer `linear()` allow custom curves.
- Wrap non-essential motion in `@media (prefers-reduced-motion: no-preference)` or reduce it under `reduce`.
- Never convey information only through animation.

Move on when you can build an animated disclosure, a skeleton loader and a hover effect that all run smoothly in the Performance panel and switch off under reduced motion.

Key concepts: transition property, @keyframes and animation, transform functions, Compositor-friendly properties, Easing functions, prefers-reduced-motion, will-change.

Mini project: Create a notification toast system in plain HTML/CSS/JS: toasts slide in, stack, auto-dismiss with a progress bar, and use a simple fade under reduced motion.

Self-check: Why does animating height often stutter while animating transform: scaleY does not?

Resources:
- [Learn CSS: Animations](https://web.dev/learn/css/animations) (web.dev)
- [Using CSS animations](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animations/Using_CSS_animations) (MDN)

## JavaScript: The Language

The core language every frontend framework is built on, from syntax to closures, prototypes and modern features.

### JavaScript Syntax and Fundamentals

core · beginner · about 12 h · https://www.internhack.in/roadmaps/tracks/frontend/js-fundamentals

Variables, operators, control flow, functions, arrays and objects: enough JavaScript to make a page interactive.

JavaScript is the only programming language browsers run natively, which makes it the centre of frontend work. Learn the language itself before any framework; frameworks change, the language underneath stays.

#### Building blocks
- **Variables**: use `const` by default, `let` when you must reassign, and avoid `var` (function-scoped and hoisted in confusing ways).
- **Primitive values**: string, number, boolean, null, undefined, bigint, symbol. Everything else is an object (including arrays and functions).
- **Operators**: arithmetic, comparison (always prefer `===` over `==`), logical `&&`, `||`, and the nullish `??`.
- **Control flow**: `if`/`else`, `switch`, `for`, `for...of` (values of an iterable), `while`, `break`/`continue`.
- **Functions**: declarations, expressions and arrow functions; parameters with defaults; returning values.

#### Arrays and objects
Most real code is data transformation. Get fluent with `map`, `filter`, `reduce`, `find`, `some`, `includes`, `sort` (beware: it mutates and sorts strings by default) and object access with dot and bracket notation. `Object.keys/values/entries` let you loop over objects.

#### How to practise
Write small programs in the browser console or Node: a to-do list in memory, a word counter, a grade calculator. Read error messages carefully; they usually tell you the exact line and cause.

#### Good enough to move on
You can write a function that takes an array of objects (say, products) and returns a filtered, sorted, transformed result without looking up the syntax, and you can debug it with `console.log` and breakpoints.

Key concepts: const, let and var, Primitive types and objects, Operators and strict equality, Control flow and loops, Functions and arrow functions, Array methods: map, filter, reduce, Objects and property access, Strings and template literals, Debugging with console and breakpoints.

Mini project: Build a command-line or console-based expense tracker: add, list, filter by category, and compute totals per month using only arrays, objects and array methods.

Self-check: What is the difference between for...of and for...in, and which one should you use to loop over an array?

Resources:
- [The Modern JavaScript Tutorial](https://javascript.info/) (javascript.info)
- [JavaScript Guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide) (MDN)
- [JavaScript Algorithms and Data Structures](https://www.freecodecamp.org/learn) (freeCodeCamp)

### Types, Coercion and Equality

core · beginner · about 4 h · https://www.internhack.in/roadmaps/tracks/frontend/js-types-coercion

Understand how JavaScript converts values behind your back, what truthy and falsy mean, and how references differ from values.

JavaScript is dynamically typed and very willing to convert values for you. That flexibility causes a whole genre of bugs, and interviewers love it.

#### Implicit coercion
- `"5" + 1` is `"51"` (string concatenation wins), but `"5" - 1` is `4` (numeric).
- `==` coerces before comparing: `0 == ""` and `null == undefined` are true. `===` never coerces, so use it by default.
- `NaN` is not equal to itself; check with `Number.isNaN()`.
- Floating point: `0.1 + 0.2 !== 0.3`. For money, work in integer cents.

#### Truthy and falsy
The falsy values are `false`, `0`, `-0`, `0n`, `""`, `null`, `undefined` and `NaN`. Everything else, including `[]`, `{}` and `"0"`, is truthy. This is why `count || 10` breaks when count is 0, and why `??` exists: it only falls back on null or undefined.

#### Values vs references
Primitives are copied by value. Objects and arrays are held by **reference**: assigning or passing them shares the same underlying object, so mutating one "copy" mutates both. Spread (`{...obj}`) makes a **shallow** copy; `structuredClone()` makes a deep one. This distinction is exactly why React insists you never mutate state.

#### Checking types
`typeof` works for primitives (but `typeof null` is "object", a historic bug); use `Array.isArray()` for arrays and `instanceof` for class instances.

Move on when you can predict the output of ten tricky coercion snippets and explain why mutating an object passed into a function affects the caller.

Key concepts: typeof and type checks, Implicit vs explicit conversion, == vs ===, Truthy and falsy values, ?? vs ||, Value vs reference, Shallow vs deep copies, Floating point and NaN.

Mini project: Write a set of 15 console assertions covering coercion, equality and copying edge cases, each with a comment explaining the result; then fix a buggy function that mutates its input.

Self-check: Why does quantity || 1 misbehave when quantity is 0, and what should you write instead?

Resources:
- [Type Conversions](https://javascript.info/type-conversions) (javascript.info)
- [Equality comparisons and sameness](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Equality_comparisons_and_sameness) (MDN)

### Functions, Scope and Closures

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/frontend/js-scope-closures

Learn lexical scope, hoisting and closures: the mechanics behind callbacks, hooks, event handlers and module privacy.

Closures are the single most important "deep" JavaScript concept for frontend developers. React hooks, event handlers, debounce utilities and module patterns all rely on them.

#### Scope
- **Lexical scope**: a function can see variables from where it was **written**, not where it is called.
- `let` and `const` are **block scoped** (inside `{}`); `var` is function scoped.
- **Hoisting**: declarations are processed before code runs. Function declarations are fully hoisted; `let`/`const` exist in a "temporal dead zone" until their line runs, so accessing them early throws.

#### Closures
A closure is a function bundled with the variables it references from its outer scope. Those variables stay alive as long as the function does.
- A counter factory: `makeCounter()` returns a function that increments a private `count`.
- A `debounce(fn, ms)` helper remembers its timer between calls.
- In React, a stale closure happens when an effect or callback captured an old value of state and never sees the new one.

#### Higher-order functions
Functions are values: they can be passed in (callbacks) and returned (factories). `map`, `addEventListener` and `setTimeout` all take functions. Currying and partial application build on the same idea.

#### Classic pitfall
A `for (var i ...)` loop that schedules timeouts logs the final value every time, because there is one shared `i`. With `let`, each iteration gets its own binding.

Move on when you can implement `debounce`, `once` and a memoize helper from scratch and explain what each closure holds on to.

Key concepts: Lexical scope, Block vs function scope, Hoisting and the temporal dead zone, Closures, Higher-order functions and callbacks, Stale closures, Currying and partial application, IIFE and the module pattern.

Mini project: Write a tiny utility library with debounce, throttle, once and memoize, plus a demo page where a search box uses your debounce to limit simulated API calls.

Self-check: Why does a loop using var print the same number from every setTimeout callback, while let does not?

Resources:
- [Variable scope, closure](https://javascript.info/closure) (javascript.info)
- [Closures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures) (MDN)

### Objects, this and Prototypes

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/frontend/js-objects-prototypes

How this is bound, how prototypal inheritance works and what classes really are under the hood.

JavaScript's object model is prototype-based. Classes exist, but they are syntax over prototypes, and `this` follows rules that trip up nearly everyone at first.

#### The four rules of this
The value of `this` depends on **how a function is called**, not where it is defined:
1. **Method call** `obj.fn()`: `this` is `obj`.
2. **Plain call** `fn()`: `undefined` in strict mode (modules are strict), the global object otherwise.
3. **Explicit binding** with `call`, `apply` or `bind`.
4. **new**: `this` is the newly created object.

**Arrow functions** have no `this` of their own; they capture it from the surrounding scope. That is why they are handy for callbacks inside methods, and why they make poor object methods. The classic bug: passing `obj.method` as a callback loses its `this`.

#### Prototypes
Every object has a hidden link (`[[Prototype]]`) to another object. Property lookups walk up this **prototype chain** until they find the key or hit `null`. Array methods like `map` live on `Array.prototype`, shared by every array.

#### Classes
`class` gives you constructors, methods, `extends`/`super`, static members, getters/setters and truly private `#fields`. Under the hood, methods are placed on the prototype. Modern frontend code uses classes less than it used to (React moved to functions), but you will meet them in libraries, Web Components and Angular.

#### Useful object tools
Destructuring, spread, `Object.freeze`, `Object.entries`, optional chaining (`user?.address?.city`), and getters for computed values.

Move on when you can explain why a method passed as an event handler loses `this`, and fix it three different ways.

Key concepts: Rules for this, Arrow functions and lexical this, call, apply and bind, Prototype chain, Classes, extends and super, Private fields and static members, Getters and setters, Object.create and Object.freeze.

Mini project: Model a small shopping cart with a Cart class (private items field, add/remove/total methods, a getter for item count) and a DiscountCart subclass, then wire a button to cart.add and fix the lost-this bug.

Self-check: Given const f = obj.greet; f(); what is this inside greet in a module, and why?

Resources:
- [Object methods, this](https://javascript.info/object-methods) (javascript.info)
- [Prototypal inheritance](https://javascript.info/prototype-inheritance) (javascript.info)
- [Inheritance and the prototype chain](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain) (MDN)

### Modern JavaScript and Error Handling

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/frontend/modern-javascript

The ES2015+ features you will see in every codebase, plus throwing, catching and reporting errors properly.

Since 2015, JavaScript gets a new edition every year. Most modern code, and every framework's documentation, assumes you know these features.

#### Features you will use daily
- **Destructuring** of objects and arrays, with defaults and renaming.
- **Spread and rest** (`...`) for copying, merging and variadic functions.
- **Template literals** for interpolation and multiline strings.
- **Optional chaining** `a?.b?.()` and **nullish coalescing** `??`.
- Shorthand properties, computed keys, default parameters.
- **Map** and **Set** for keyed collections and uniqueness; `WeakMap` for caches tied to object lifetime.
- **Iterators and generators** (`function*`), which power `for...of`.
- Newer additions: `Array.prototype.at()`, `toSorted()`/`toReversed()` (non-mutating), `Object.groupBy()`, `structuredClone()`.

#### Error handling
- `throw new Error("message")` with a useful message; subclass `Error` for domain errors (`class ValidationError extends Error`).
- `try...catch...finally` handles synchronous code and awaited promises. The `cause` option (`new Error("Save failed", { cause: err })`) preserves the original error.
- Unhandled promise rejections do not crash the page but are easy to miss; listen for `unhandledrejection` and `error` on `window` to report them.
- Do not swallow errors with an empty catch. Either handle it (show UI, retry) or rethrow.

#### Pitfall
Catching too broadly hides bugs. Catch where you can do something meaningful, typically at a UI boundary that shows the user a message.

Move on when you can read unfamiliar modern code without pausing on syntax and your async code never fails silently.

Key concepts: Destructuring, Spread and rest, Optional chaining and nullish coalescing, Map, Set and WeakMap, Iterators and generators, Non-mutating array methods, try, catch, finally, Custom errors and error cause, Global error and unhandledrejection events.

Mini project: Refactor an old-style ES5 script (var, concatenation, manual loops) into modern syntax, add a custom ValidationError, and add a global error listener that shows a friendly banner.

Self-check: Why is const { user: { name } = {} } = response safer than response.user.name?

Resources:
- [The Modern JavaScript Tutorial](https://javascript.info/) (javascript.info)
- [Error handling, try...catch](https://javascript.info/try-catch) (javascript.info)
- [JavaScript reference](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference) (MDN)

## JavaScript Meets the Browser

Drive the page with the DOM and events, and handle asynchronous work: timers, promises, the event loop and network requests.

### DOM Manipulation

core · beginner · about 6 h · https://www.internhack.in/roadmaps/tracks/frontend/dom

Select, create, update and remove elements with the Document Object Model, and understand what frameworks automate for you.

The **DOM** is the live object tree the browser builds from your HTML. JavaScript reads and changes it to make pages interactive. Frameworks like React exist to manage DOM updates for you, and you will use them far better if you have done it by hand first.

#### Core operations
- **Select**: `document.querySelector(".card")` and `querySelectorAll` (returns a static NodeList you can `forEach`).
- **Create and insert**: `document.createElement`, `append`, `prepend`, `before`, `after`, `replaceWith`, `remove`.
- **Read and change content**: `textContent` (safe) vs `innerHTML` (parses HTML, dangerous with user input because of XSS).
- **Attributes and classes**: `setAttribute`, `dataset` for `data-*`, and `classList.add/remove/toggle`.
- **Styles**: prefer toggling classes over setting `element.style` directly.

#### Performance habits
- Batch changes: build nodes in a `DocumentFragment` or a `<template>` and insert once.
- Avoid reading layout (`offsetWidth`, `getBoundingClientRect`) in the middle of writes; that forces synchronous layout.
- For long lists, render only what is visible (virtualisation) or paginate.

#### Observers
`IntersectionObserver` (is this element on screen, great for lazy loading and infinite scroll), `ResizeObserver` (did this element change size) and `MutationObserver` (did the DOM change) replace many polling hacks.

Move on when you can build a small interactive UI (say, a filterable list) with vanilla JavaScript and no framework, keeping it free of innerHTML with user data.

Key concepts: querySelector and querySelectorAll, Creating and inserting nodes, textContent vs innerHTML, classList and dataset, template element and fragments, Traversal: parent, children, closest, IntersectionObserver and ResizeObserver, MutationObserver.

Mini project: Build a vanilla JS contact list: render from an array, add and delete contacts, filter by search text, and lazy-load avatars with IntersectionObserver.

Self-check: Why is setting innerHTML with a user's comment dangerous, and what should you use instead?

Resources:
- [Document Object Model (DOM)](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model) (MDN)
- [Browser: Document, Events, Interfaces](https://javascript.info/document) (javascript.info)

### Events and Event Delegation

core · beginner · about 5 h · https://www.internhack.in/roadmaps/tracks/frontend/events

Respond to clicks, keys, input and more; understand bubbling, capturing, default actions and delegation.

Events are how the browser tells your code that something happened: a click, a key press, a form submit, a resize, a network response. Handling them well is the core of interactivity.

#### Listening
`element.addEventListener("click", handler)` attaches a listener; `removeEventListener` needs the **same function reference** to detach it. The handler receives an **event object** with details such as `target`, `currentTarget`, `key` and `clientX`.

#### Propagation
Events travel in three phases: **capture** (from window down), **target**, then **bubble** (back up). Most listeners run in the bubble phase.
- `event.target` is where the event started; `event.currentTarget` is the element whose listener is running.
- `stopPropagation()` stops the journey (use rarely, it breaks other code's assumptions).
- `preventDefault()` cancels the default action: following a link, submitting a form, scrolling.

#### Delegation
Instead of 500 listeners on 500 list items, attach one to the parent and check `event.target.closest("li")`. It uses less memory and automatically covers items added later. React uses a form of this internally.

#### Choosing the right events
- `input` fires on every change, `change` on commit.
- Use `submit` on forms, not click on the button, so Enter works.
- `pointer` events unify mouse, touch and pen.
- `keydown` for shortcuts; check `event.key` (not deprecated `keyCode`).
- Mark scroll and touch listeners `{ passive: true }` for smoother scrolling, and use `{ once: true }` or an `AbortController` signal to clean up.

Move on when you can build a keyboard-accessible dropdown menu that closes on outside click and Escape, using delegation for its items.

Key concepts: addEventListener and removal, The event object, Bubbling and capturing, target vs currentTarget, preventDefault and stopPropagation, Event delegation, Pointer and keyboard events, passive, once and AbortController signals, Custom events.

Mini project: Build a kanban board in vanilla JS with delegated click handlers for cards, keyboard shortcuts for moving cards between columns, and an outside-click close for the card menu.

Self-check: Why does event delegation keep working for list items added after the listener was attached?

Resources:
- [Introduction to browser events](https://javascript.info/introduction-browser-events) (javascript.info)
- [Event delegation](https://javascript.info/event-delegation) (javascript.info)
- [Event reference](https://developer.mozilla.org/en-US/docs/Web/Events) (MDN)

### Asynchronous JavaScript: Callbacks, Promises and async/await

core · intermediate · about 7 h · https://www.internhack.in/roadmaps/tracks/frontend/async-javascript

Handle work that finishes later, from callbacks to promises to async/await, including parallelism, cancellation and error handling.

Almost everything interesting on the web is asynchronous: network requests, timers, user input, reading files. JavaScript runs on a single thread, so it cannot wait by blocking; it registers work to finish later.

#### Three generations
1. **Callbacks**: pass a function to run when done (`setTimeout(fn, 1000)`). Nesting many leads to "callback hell" and scattered error handling.
2. **Promises**: an object representing a future value that is pending, then fulfilled or rejected. Chain with `.then()`, handle failures with `.catch()`, clean up with `.finally()`.
3. **async/await**: syntax over promises. An `async` function always returns a promise; `await` pauses that function (not the whole page) until the promise settles. Use `try/catch` for errors.

#### Combinators
- `Promise.all` runs in parallel and rejects if any fails.
- `Promise.allSettled` waits for all and reports each result.
- `Promise.race` and `Promise.any` take the first to settle or succeed.

#### Common mistakes
- Awaiting in a loop when requests are independent. Start them together and `await Promise.all(...)` instead.
- Forgetting `await`, so you get a Promise object instead of data.
- Not returning a promise from a `.then()` callback, breaking the chain.
- Ignoring **cancellation**: use `AbortController` so a stale search request does not overwrite newer results (a race condition).

#### Good enough to move on
You can wrap a callback API in a promise, fetch three endpoints in parallel with proper error handling, and cancel an in-flight request when the user types again.

Key concepts: Callbacks and callback hell, Promise states and chaining, async and await, Error handling in async code, Promise.all, allSettled, race, any, Sequential vs parallel awaits, AbortController and cancellation, Promisifying callback APIs.

Mini project: Build a movie search box that queries a free public API, debounces input, cancels stale requests with AbortController, and shows loading, empty and error states.

Self-check: What happens if one of three promises passed to Promise.all rejects, and when would you choose allSettled instead?

Resources:
- [Promises, async/await](https://javascript.info/async) (javascript.info)
- [Using promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises) (MDN)

### The Event Loop

core · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/frontend/event-loop

See how the call stack, task queue, microtask queue and rendering interleave, and why long tasks freeze the UI.

The event loop explains when your code actually runs. It turns confusing ordering bugs into predictable behaviour and is a favourite interview topic.

#### The pieces
- **Call stack**: the function currently executing and the ones that called it. JavaScript runs one stack frame at a time.
- **Web APIs**: timers, network, DOM events run outside the JS engine and queue callbacks when done.
- **Task (macrotask) queue**: `setTimeout`, `setInterval`, I/O and UI event callbacks.
- **Microtask queue**: promise reactions (`.then`, code after `await`) and `queueMicrotask`. It has priority.

#### The loop, simplified
1. Run one task to completion.
2. Drain **all** microtasks (including ones queued by other microtasks).
3. If it is time, **render** (style, layout, paint), running `requestAnimationFrame` callbacks first.
4. Repeat.

So `console.log("A"); setTimeout(() => console.log("B")); Promise.resolve().then(() => console.log("C")); console.log("D");` prints A, D, C, B.

#### Why it matters in practice
- A long synchronous task (heavy loop, big JSON parse) blocks input and rendering. Anything over 50ms is a "long task" and hurts **Interaction to Next Paint**.
- Break up work with `setTimeout`, `scheduler.yield()` where supported, or move it to a Web Worker.
- Use `requestAnimationFrame` for visual updates so they line up with frames.
- An infinite chain of microtasks can starve rendering completely.

Move on when you can predict the log order of mixed timers, promises and awaits, and you can spot a long task in the Performance panel.

Key concepts: Call stack, Task queue, Microtask queue, Rendering steps and requestAnimationFrame, Long tasks and main-thread blocking, Yielding to the main thread, Node.js event loop differences.

Mini project: Create an interactive demo page where buttons trigger a blocking loop, a chunked loop and a worker-free yielding version, with a spinning CSS animation and a counter showing which approach keeps the UI responsive.

Self-check: In what order do a setTimeout(0) callback and a resolved promise's then callback run, and why?

Resources:
- [Event loop: microtasks and macrotasks](https://javascript.info/event-loop) (javascript.info)
- [What the heck is the event loop anyway? (Philip Roberts)](https://www.youtube.com/watch?v=8aGhZQkoFbQ) (JSConf EU)

### Fetch and Working with APIs

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/frontend/fetch-api

Make HTTP requests from the browser with fetch, handle JSON, headers, errors, loading states and CORS.

`fetch` is the browser's built-in HTTP client and the foundation that data libraries wrap. Know it well before adopting abstractions.

#### The basics
`const res = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) });` then `await res.json()`.
- **fetch only rejects on network failure.** A 404 or 500 still resolves, so always check `res.ok` or `res.status` and throw your own error.
- Read the body once, with the right method: `json()`, `text()`, `blob()`, `formData()`.
- Send files with `FormData` and let the browser set the multipart header.
- `credentials: "include"` sends cookies to other origins (the server must allow it).

#### Building a small API layer
Wrap fetch in a helper that sets the base URL, adds auth headers, parses JSON, converts non-2xx responses into typed errors and supports `AbortSignal`. Every component then calls `api.get("/jobs")` instead of repeating boilerplate.

#### UI states
Every request has at least four states: idle, loading, success and error (plus empty). Design each one. Show skeletons instead of spinners for content, keep the previous data while refetching and let users retry errors.

#### CORS in one paragraph
Browsers block reading responses from a different origin unless the server sends `Access-Control-Allow-Origin`. Requests with custom headers or JSON bodies trigger an `OPTIONS` **preflight**. CORS is fixed on the **server** (or with a dev proxy), never by a frontend flag.

Move on when you have built a small API client with error handling and used it to power a page with all loading and error states.

Key concepts: fetch request options, Checking res.ok and status, JSON, text, blob and FormData bodies, Headers and credentials, Loading, error and empty states, Reusable API client wrapper, CORS and preflight requests, Streaming responses.

Mini project: Build a GitHub profile viewer that uses the public GitHub REST API through your own api helper, handles 404 and rate-limit errors, and shows skeleton loaders.

Self-check: Your fetch call to an endpoint returning 500 went into the success branch. Why, and how do you fix it?

Resources:
- [Using the Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) (MDN)
- [Fetch](https://javascript.info/fetch) (javascript.info)
- [Cross-Origin Resource Sharing (CORS)](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS) (MDN)

## Everyday Workflow and Tooling

Version control, modules, package managers, bundlers and code quality tools that every professional project uses.

### Git and GitHub

core · beginner · about 6 h · https://www.internhack.in/roadmaps/tracks/frontend/git

Track changes, branch, merge and collaborate through pull requests: the workflow every team expects on day one.

Git records snapshots of your project so you can experiment safely, undo mistakes and work with others. GitHub (or GitLab, Bitbucket) hosts repositories and adds collaboration features around them.

#### The daily loop
`git status` to see what changed, `git add` to stage, `git commit -m "..."` to snapshot, `git push` to share, `git pull` to receive. Learn what the **working tree**, **staging area** and **repository** are; most confusion disappears once you picture those three places.

#### Branching and merging
- Create a branch per feature or fix (`git switch -c feature/login`).
- **Merge** combines histories with a merge commit; **rebase** replays your commits on top of another branch for a linear history. Never rebase commits others have already pulled.
- **Conflicts** happen when two branches change the same lines. Read the markers, choose the right result, test, then commit.

#### Collaboration on GitHub
- Fork or clone, branch, push, open a **pull request**, get review, address comments, merge.
- Write commit messages that explain why (many teams use Conventional Commits like `feat:` and `fix:`).
- Use `.gitignore` for `node_modules`, build output and `.env` files. Secrets committed once live in history forever.
- Issues, project boards and GitHub Actions round out the workflow.

#### Getting out of trouble
`git log --oneline`, `git diff`, `git restore`, `git revert` (safe undo on shared branches), `git reset` (rewrites local history), `git stash` and `git reflog` (finds "lost" commits).

Move on when you can open a PR from a feature branch, resolve a merge conflict and revert a bad commit without panicking.

Key concepts: Working tree, staging and commits, Branches and switching, Merge vs rebase, Resolving conflicts, Remotes, push and pull, Pull requests and code review, .gitignore and secrets, revert, reset, stash and reflog, Conventional commits.

Mini project: Put all your projects so far on GitHub; for one of them, make a feature branch, open a pull request with a clear description, deliberately create and resolve a conflict, and merge it.

Self-check: When is git revert the right way to undo a commit, and when is git reset acceptable?

Resources:
- [Pro Git](https://git-scm.com/book/en/v2) (git-scm.com)
- [Get started with GitHub](https://docs.github.com/en/get-started) (GitHub Docs)
- [Learn Git Branching](https://learngitbranching.js.org/)

### JavaScript Modules

core · beginner · about 3 h · https://www.internhack.in/roadmaps/tracks/frontend/js-modules

Split code into files with ES modules, understand imports and exports, and know how CommonJS differs.

Modules let you split code into files with explicit dependencies. Every modern frontend project is a graph of modules that a bundler or the browser stitches together.

#### ES modules (ESM)
- `export` named values (`export function formatDate`) or a single `export default`.
- `import { formatDate } from "./dates.js"`, `import * as utils`, and renaming with `as`.
- Modules are **strict mode**, have their own scope (no accidental globals) and are evaluated **once**; every importer shares the same instance.
- In the browser, `<script type="module">` loads ESM natively, deferred by default.
- **Dynamic import** `await import("./chart.js")` loads code on demand and is the basis of code splitting.

#### CommonJS
Node's older system uses `require()` and `module.exports`. You will still see it in config files and older packages. Mixing the two causes the classic "Cannot use import statement outside a module" error; `"type": "module"` in package.json, or `.mjs`/`.cjs` extensions, decide how Node treats a file.

#### Good practice
- Prefer **named exports**: they autocomplete better, are easier to rename safely and tree-shake cleanly.
- Keep modules focused. Avoid "barrel" files that re-export everything if they slow builds or hide circular imports.
- **Circular dependencies** can produce `undefined` imports at runtime; restructure so shared code lives in a third module.

Move on when you can organise a vanilla project into feature modules and lazy-load a heavy module with dynamic import.

Key concepts: Named and default exports, Import syntax, script type=module, Dynamic import(), CommonJS require and module.exports, type: module and .mjs/.cjs, Circular dependencies.

Mini project: Split your earlier vanilla project into ES modules (api, state, render, utils) loaded with script type=module, and lazy-load a charts module only when the user opens a stats tab.

Self-check: Why do tools find it easier to tree-shake named ES module exports than CommonJS exports?

Resources:
- [JavaScript modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules) (MDN)
- [Modules, introduction](https://javascript.info/modules-intro) (javascript.info)

### Package Managers

core · beginner · about 3 h · https://www.internhack.in/roadmaps/tracks/frontend/package-managers

Install, version and script your dependencies with npm (recommended), and know when pnpm, Yarn or Bun make sense.

A package manager downloads third-party code from the npm registry, records exactly which versions you use and runs project scripts. Every frontend project has a `package.json`.

#### Core concepts
- `dependencies` ship with your app; `devDependencies` are build and test tools.
- **Semantic versioning**: `MAJOR.MINOR.PATCH`. `^1.4.2` allows minor and patch updates; `~1.4.2` only patches. Major versions may break things.
- The **lockfile** (`package-lock.json`, `pnpm-lock.yaml`, `yarn.lock`, `bun.lock`) pins the exact resolved tree. Commit it. Use `npm ci` in CI for clean, reproducible installs.
- **Scripts**: `"dev"`, `"build"`, `"test"`, `"lint"` in package.json, run with `npm run build`. `npx` runs a package binary without installing it globally.

#### Which one?
- **npm** (recommended to start): ships with Node, works everywhere, and every tutorial assumes it.
- **pnpm**: a content-addressed store with hard links, so it is fast and disk-efficient, and stricter about undeclared dependencies. Excellent for monorepos via workspaces.
- **Yarn**: popularised lockfiles and workspaces; modern Yarn (Berry) offers Plug'n'Play.
- **Bun**: an all-in-one runtime, package manager, bundler and test runner focused on speed.
Pick one per repo and stick to it; mixing lockfiles causes drift.

#### Hygiene
Check a package's maintenance, size and weekly downloads before adding it. Run `npm audit` or enable Dependabot or Renovate, and remember that every dependency is code from strangers running on your machine and your users' browsers.

Move on when you can explain every field in your package.json and recover a broken `node_modules` with a clean install.

Key concepts: npm, pnpm, Yarn, Bun, package.json and scripts, Semantic versioning and ranges, Lockfiles and npm ci, npx and binaries, Workspaces and monorepos, npm audit and dependency updates.

Mini project: Initialise a project with npm, add a date library and a dev tool, write dev/build/lint scripts, then recreate the same setup with pnpm and compare install times and node_modules structure.

Self-check: What does the caret in ^2.3.1 allow, and why should the lockfile still be committed?

Resources:
- [npm Docs](https://docs.npmjs.com/) (npm)
- [pnpm Motivation](https://pnpm.io/motivation) (pnpm)
- [Bun documentation](https://bun.sh/docs) (Bun)

### Build Tools and Bundlers

core · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/frontend/build-tools

Use Vite (recommended) for dev servers and production builds, and understand what webpack, esbuild, Rollup and Turbopack do.

Browsers can run modules directly, but production apps still need a build step: to compile TypeScript and JSX, bundle hundreds of modules into efficient chunks, minify, hash filenames for caching and process CSS and images.

#### What a build tool does
- **Dev server** with hot module replacement (HMR): edits appear instantly without losing state.
- **Transpiling**: TypeScript, JSX and newer syntax into what target browsers support.
- **Bundling and code splitting**: combine modules, split by route or dynamic import.
- **Tree shaking**: drop unused exports.
- **Minification and hashing**: `app.3f9a1c.js` can be cached forever because a change produces a new name.
- **Environment variables**: inject build-time config (only public values).

#### The landscape
- **Vite** (recommended): serves native ESM in development for near-instant startup, uses a fast bundler for production and has a rich plugin ecosystem. It is the default for new React, Vue and Svelte projects.
- **webpack**: the long-time standard; hugely configurable with loaders and plugins. You will meet it in older or enterprise codebases.
- **esbuild**: an extremely fast Go-based bundler/transpiler, often used inside other tools.
- **Rollup**: excellent for libraries, with clean ESM output; its API inspired Vite's plugins.
- **Turbopack** and **Rspack**: Rust-based successors aimed at webpack-scale apps (Turbopack powers Next.js dev).

#### Good enough to move on
You can scaffold a Vite project, explain what `vite build` outputs, add an environment variable, configure a path alias and inspect bundle size. Deep webpack configuration is something you learn when a job requires it.

Key concepts: Vite, webpack, esbuild, Rollup, Turbopack and Rspack, Dev server and HMR, Transpiling and browser targets, Tree shaking and code splitting, Content hashing and minification, Bundle analysis.

Mini project: Move your vanilla modules project onto Vite, add an environment variable for the API base URL and a path alias, build it, and use a bundle visualiser plugin to find the largest dependency.

Self-check: Why can a file named app.3f9a1c.js be cached for a year while index.html should not be?

Resources:
- [Vite Guide](https://vite.dev/guide/) (Vite)
- [webpack Concepts](https://webpack.js.org/concepts/) (webpack)
- [esbuild](https://esbuild.github.io/) (esbuild)

### Linting and Formatting

core · beginner · about 2 h · https://www.internhack.in/roadmaps/tracks/frontend/linting-formatting

Catch bugs automatically with ESLint and end style debates with Prettier, wired into your editor and commits.

Linters and formatters are cheap, automatic code reviewers. Teams adopt them so humans can review logic instead of arguing about semicolons.

#### ESLint: finds problems
ESLint statically analyses code and reports likely bugs: unused variables, missing `await`, unreachable code, misuse of React hooks (`eslint-plugin-react-hooks` is essential), accessibility issues in JSX (`eslint-plugin-jsx-a11y`). Modern ESLint uses a **flat config** file (`eslint.config.js`) and `typescript-eslint` for type-aware rules. Many rules can auto-fix.

#### Prettier: formats code
Prettier reformats code to one consistent style (quotes, wrapping, trailing commas) with very few options on purpose. Run it on save in your editor. Let Prettier own formatting and ESLint own correctness; `eslint-config-prettier` turns off ESLint rules that would conflict. Biome is a newer, faster tool that combines both roles.

#### Automate it
- Editor integration: format on save, show lint errors inline.
- Pre-commit hooks with **husky** and **lint-staged** run checks on changed files only.
- Run `lint` and `typecheck` in CI so rules are enforced for everyone.
- An `.editorconfig` keeps indentation consistent across editors.

#### Pitfall
Do not enable hundreds of stylistic rules nobody agreed on. Start with recommended presets, add rules when a real bug slips through, and treat warnings you ignore as noise to either fix or delete.

Move on when your projects lint and format automatically on save and in CI, with zero warnings.

Key concepts: ESLint flat config, Recommended rule sets, Prettier, eslint-config-prettier, Editor format on save, husky and lint-staged, Biome.

Mini project: Add ESLint and Prettier to your Vite project with a pre-commit hook, then deliberately commit an unused variable and a misformatted file to confirm they are blocked or fixed.

Self-check: Why should ESLint and Prettier have separate responsibilities, and what goes wrong if both enforce formatting?

Resources:
- [ESLint: Getting Started](https://eslint.org/docs/latest/use/getting-started) (ESLint)
- [Prettier Docs](https://prettier.io/docs/) (Prettier)

## Styling at Scale

How teams keep CSS maintainable as an app grows: pick one styling approach and learn it well.

### Tailwind CSS

recommended · beginner · about 6 h · https://www.internhack.in/roadmaps/tracks/frontend/tailwind

Utility-first styling that keeps design decisions consistent and colocated with markup; our recommended default for new projects.

Plain CSS works, but in a large app you fight naming, dead styles nobody dares delete, and specificity battles. Tailwind solves this by giving you small, single-purpose classes (`flex`, `gap-4`, `text-sm`, `md:grid-cols-3`) that you compose directly in markup. The build step scans your files and emits only the classes you actually used.

#### Why it is our default
- **Consistency**: spacing, colours and font sizes come from a shared scale, so you stop inventing `margin: 13px`.
- **Locality**: the styles for a component live in the component. Deleting the component deletes its styles.
- **Speed**: no context switching between files, and responsive or state variants are just prefixes: `hover:`, `focus-visible:`, `dark:`, `md:`.
- **Ecosystem**: shadcn/ui, many templates and most modern React tooling assume it.

#### How to use it well
- Configure your **theme** (colours, fonts, radii) with CSS variables so the design system lives in one place.
- Extract **components**, not `@apply` soup. If a button's class list repeats, make a `Button` component.
- Use a class-merging helper (`clsx` plus `tailwind-merge`) for conditional classes and overrides.
- Install the editor extension for autocomplete and class sorting.

#### Pitfalls
- Tailwind is still CSS. If you do not understand flexbox, grid and the box model, utilities will not save you.
- Never build class names dynamically (`"bg-" + color`); the scanner cannot see them. Map values to full class strings.
- Long class lists are fine, but readable ordering and extraction into components matter.

#### Good enough to move on
You can build a responsive, dark-mode-aware card grid and navbar using only utilities, customise the theme colours, and explain why dynamic class strings break.

Key concepts: Utility-first mindset, Responsive and state variants, Theme configuration with CSS variables, Dark mode, Conditional classes with clsx and tailwind-merge, Extracting components vs @apply, Arbitrary values and plugins.

Mini project: Rebuild one of your earlier HTML/CSS pages with Tailwind: responsive navigation, a card grid and a pricing table, with a working dark mode toggle driven by a class on the html element.

Self-check: Why does writing className={`text-${size}`} fail in production, and how do you fix it?

Resources:
- [Tailwind CSS Documentation](https://tailwindcss.com/docs) (Tailwind CSS)
- [Styling with utility classes](https://tailwindcss.com/docs/styling-with-utility-classes) (Tailwind CSS)

### CSS Modules

alternative · beginner · about 3 h · https://www.internhack.in/roadmaps/tracks/frontend/css-modules

Write normal CSS files whose class names are scoped to one component automatically, with zero runtime cost.

CSS Modules keep plain CSS but fix its biggest problem at scale: global class names. When you import `Button.module.css` into a component, the build tool rewrites `.primary` into something unique like `Button_primary__x7f2a`, so two components can both use `.title` without colliding.

#### How it works
```
import styles from "./Card.module.css";
<div className={styles.card}>...</div>
```
Vite, Next.js and most bundlers support CSS Modules with no configuration. Each file is its own scope; use `:global(...)` sparingly when you really need to reach outside.

#### Strengths
- You write real CSS: every feature (grid, container queries, nesting, custom properties) works as-is.
- No runtime library, so no performance cost and full compatibility with Server Components.
- Styles are deleted along with the component that imports them.

#### Patterns
- Keep one module per component, named after it.
- Use **custom properties** for theming and pass dynamic values through `style={{ "--progress": value }}`.
- Combine classes with a small helper such as `clsx`.
- Share design tokens through a global `tokens.css` of variables, not by importing other modules.

#### Pitfalls
Composition across files (`composes:`) can get tangled, and you still need your own spacing and colour scale discipline. TypeScript needs a small declaration or plugin to type the imported class names.

#### Good enough to move on
You can style a component library of 5 to 10 components with CSS Modules, theme them via variables, and explain how the class name scoping is generated.

Key concepts: Local scoping and generated class names, Importing modules into components, :global escapes, Theming with custom properties, composes and sharing styles, Typing class names in TypeScript.

Mini project: Create Button, Card, Badge and Modal components styled with CSS Modules, themed by a global tokens.css, and verify in DevTools that class names are scoped.

Self-check: Two components both define a .title class in their own module file. Why do they not conflict?

Resources:
- [CSS Modules in Vite](https://vite.dev/guide/features#css-modules) (Vite)
- [CSS Modules specification](https://github.com/css-modules/css-modules) (GitHub)

### Sass and Preprocessors

alternative · beginner · about 3 h · https://www.internhack.in/roadmaps/tracks/frontend/sass

Variables, nesting, mixins and partials compiled to CSS; still common in existing codebases even though native CSS has caught up.

Sass (using the SCSS syntax) was the tool that made large stylesheets bearable before CSS had variables and nesting. You write `.scss` files and a compiler outputs plain CSS. Many design systems, Bootstrap themes and enterprise apps still use it, so you should be able to read and change it.

#### Core features
- **Variables**: `$brand: #3355ff;` resolved at compile time (unlike CSS custom properties, which live at runtime).
- **Nesting**: write child selectors inside parents. Keep it shallow; deep nesting produces over-specific selectors.
- **Partials and modules**: split styles into `_buttons.scss` and load them with `@use`, which namespaces members. `@import` is deprecated.
- **Mixins and functions**: reusable chunks such as a `respond-to(md)` media query mixin, or colour maths.
- **Loops and maps**: generate utility classes from a map of spacing values.

#### Sass vs native CSS today
Native CSS now has custom properties, nesting, `color-mix()` and cascade layers. That means new projects often need no preprocessor. Sass still shines for heavy compile-time generation and in codebases already built on it.

#### Pitfalls
- Using Sass variables for things that should change at runtime (themes). Use CSS custom properties there.
- Nesting four levels deep to mirror HTML. This creates fragile, high-specificity selectors.
- Mixing `@import` and `@use` in one codebase.

#### Good enough to move on
You can read an SCSS codebase, add a partial, write a breakpoint mixin and explain when a Sass variable vs a CSS custom property is the right choice.

Key concepts: SCSS syntax and compilation, Variables vs CSS custom properties, Nesting and the parent selector &, @use, partials and namespaces, Mixins and functions, Maps and loops, BEM naming.

Mini project: Convert a plain CSS stylesheet into SCSS partials with a breakpoint mixin, a spacing map that generates margin utilities, and CSS custom properties for a light/dark theme.

Self-check: Why can a Sass variable not power a runtime dark mode toggle while a CSS custom property can?

Resources:
- [Sass Basics](https://sass-lang.com/guide/) (Sass)
- [Sass Documentation](https://sass-lang.com/documentation/) (Sass)

### CSS-in-JS

alternative · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/frontend/css-in-js

Style components with JavaScript (styled-components, Emotion) or zero-runtime tools (vanilla-extract, Panda); know the trade-offs.

CSS-in-JS lets you write styles inside JavaScript or TypeScript files, usually colocated with the component and able to use props directly. It became popular with React and powers libraries like MUI and Chakra.

#### Two families
- **Runtime libraries** such as **styled-components** and **Emotion** generate and inject CSS in the browser as components render. They are flexible (`color: ${p => p.variant === "danger" ? "red" : "black"}`) but add JavaScript cost and do not fit well with React Server Components or streaming SSR.
- **Zero-runtime libraries** such as **vanilla-extract**, **Panda CSS**, **Linaria** and **StyleX** extract static CSS at build time. You keep type-safe, colocated styles without shipping a style engine to users.

#### Strengths
- Real scoping with no naming conventions.
- Type-safe themes and variants, and styles that can read component props.
- Easy deletion: styles go when the component goes.

#### Trade-offs
- Runtime libraries cost performance (serialising styles during render) and complicate SSR setup.
- Heavier tooling and a steeper debugging story than plain CSS.
- Much of the industry's new work has moved to Tailwind or zero-runtime options for these reasons.

#### When to choose it
Pick it when you join a codebase or component library that already uses it, or when you need strongly typed variant APIs and choose a zero-runtime tool. For a new app, Tailwind or CSS Modules is usually simpler.

#### Good enough to move on
You can build a themed, variant-driven Button with one CSS-in-JS library and explain why runtime CSS-in-JS conflicts with Server Components.

Key concepts: Runtime vs zero-runtime, styled-components and Emotion, vanilla-extract, Panda CSS, StyleX, Theming and typed variants, SSR and Server Components constraints, Performance cost of runtime styles.

Mini project: Implement the same Button component (sizes, variants, disabled state, theme) twice: once with a runtime library and once with a zero-runtime library, then compare bundle size and SSR output.

Self-check: What work does a runtime CSS-in-JS library do on every render that a zero-runtime one moves to build time?

Resources:
- [styled-components documentation](https://styled-components.com/docs) (styled-components)
- [vanilla-extract](https://vanilla-extract.style/) (vanilla-extract)
- [Panda CSS](https://panda-css.com/) (Panda CSS)

## TypeScript for Frontend Developers

Add a type system to JavaScript so editors catch mistakes early and large codebases stay refactorable.

### TypeScript Fundamentals

core · intermediate · about 10 h · https://www.internhack.in/roadmaps/tracks/frontend/typescript-basics

Annotations, inference, interfaces, unions and narrowing: the daily TypeScript every frontend job expects.

TypeScript is JavaScript plus a static type checker. The types are erased at build time, so nothing changes at runtime, but your editor and CI now catch typos, wrong arguments, missing null checks and broken refactors before users do. Most professional frontend codebases are written in it.

#### The essentials
- **Inference first**: `const count = 0` is already a `number`. Annotate function parameters and public APIs; let the rest be inferred.
- **Object shapes** with `type` or `interface`. Either is fine; pick one convention.
- **Union types**: `type Status = "idle" | "loading" | "error"` models real states far better than booleans.
- **Optional and nullable** values: `name?: string`, `user: User | null`, with optional chaining `user?.name`.
- **Arrays, tuples and records**: `string[]`, `[number, number]`, `Record<string, number>`.
- **Narrowing**: `typeof`, `in`, equality checks and discriminated unions (`if (result.ok)`) let TypeScript know which branch you are in.

#### unknown, any and assertions
`any` switches checking off and spreads silently; avoid it. Use `unknown` for data you have not validated (API responses, `JSON.parse`) and narrow it. Type assertions (`as User`) are promises you make to the compiler; they are not checks.

#### Setup
Turn on `"strict": true` from day one. Use `tsc --noEmit` in CI because many bundlers strip types without checking them.

#### Good enough to move on
You can type a small app's data model, functions and API responses under strict mode without reaching for `any`, and use a discriminated union for loading/success/error state.

Key concepts: Type annotations and inference, type aliases and interfaces, Union and literal types, Optional, null and undefined, Narrowing and type guards, Discriminated unions, any vs unknown vs never, Typing functions and callbacks, Strict mode.

Mini project: Port a vanilla JavaScript project (for example your fetch-based weather or movie app) to TypeScript with strict mode, typing API responses as unknown and narrowing them before use.

Self-check: Why is `const data = await res.json() as User` less safe than parsing into unknown and narrowing?

Resources:
- [The TypeScript Handbook](https://www.typescriptlang.org/docs/handbook/intro.html) (TypeScript)
- [TypeScript for JavaScript Programmers](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html) (TypeScript)
- [TypeScript Playground](https://www.typescriptlang.org/play) (TypeScript)

### Generics and Advanced Types

core · advanced · about 8 h · https://www.internhack.in/roadmaps/tracks/frontend/typescript-advanced

Write reusable, precise types with generics, utility types, keyof, mapped and conditional types.

Once basic annotations feel natural, you will hit code that works for many types: a `useFetch` hook, a table component, a typed event emitter. Generics and type operators let you describe these precisely instead of falling back to `any`.

#### Generics
A generic is a type parameter: `function first<T>(items: T[]): T | undefined`. The caller's argument decides `T`. Add **constraints** with `extends` (`<T extends { id: string }>`) and defaults when useful. React components and hooks are generic all the time: `useState<User | null>(null)`.

#### Utility types you will use weekly
- `Partial<T>`, `Required<T>`, `Readonly<T>`
- `Pick<T, K>` and `Omit<T, K>` to derive form or API shapes from a model
- `Record<K, V>`, `ReturnType<F>`, `Parameters<F>`, `Awaited<T>`, `NonNullable<T>`

#### Type operators
- `keyof T` gives the union of keys; indexed access `T["name"]` gets a property type.
- `typeof value` lifts a runtime value into a type, great with `as const` objects.
- **Mapped types** transform every key: `{ [K in keyof T]: T[K] | null }`.
- **Conditional types** and `infer` branch on types; mostly library territory.
- **Template literal types** build string unions like ``on${Capitalize<Event>}``.
- `satisfies` checks a value against a type while keeping its narrow inferred type.

#### Pitfalls
Clever types are a maintenance cost. If a type needs a paragraph of explanation, simplify it. Prefer deriving types from one source of truth (a Zod schema or a model type) over duplicating them.

#### Good enough to move on
You can write a generic list component or fetch helper, derive form types with `Pick` and `Partial`, and read the types in a library's `.d.ts` file.

Key concepts: Generic functions and constraints, Built-in utility types, keyof, typeof and indexed access, as const and satisfies, Mapped types, Conditional types and infer, Template literal types.

Mini project: Write a typed fetch helper `request<T>(url, schema)` and a generic `DataTable<T>` whose column definitions only accept keys of T, then derive create/update DTO types from one model with utility types.

Self-check: What does `Omit<User, "id" | "createdAt">` produce, and why is it better than writing a second interface by hand?

Resources:
- [Generics](https://www.typescriptlang.org/docs/handbook/2/generics.html) (TypeScript)
- [Utility Types](https://www.typescriptlang.org/docs/handbook/utility-types.html) (TypeScript)
- [Creating Types from Types](https://www.typescriptlang.org/docs/handbook/2/types-from-types.html) (TypeScript)

### TypeScript Configuration and Tooling

recommended · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/frontend/typescript-tooling

tsconfig options, declaration files, typing third-party code and keeping type checks in your workflow.

Knowing the type system is half the job; the other half is configuring a project so TypeScript helps rather than annoys.

#### tsconfig.json essentials
- `strict`: turns on the checks that matter (`strictNullChecks`, `noImplicitAny` and friends).
- `target` and `lib`: which JavaScript features and built-in APIs (including `DOM`) are available.
- `module` and `moduleResolution`: use `"bundler"` for Vite-style apps and `"NodeNext"` for Node packages.
- `jsx`: `"react-jsx"` for React projects.
- `paths`: import aliases like `@/components` (the bundler must agree).
- `noEmit`: let the bundler produce JavaScript while `tsc` only type checks.
- Extra safety worth enabling: `noUncheckedIndexedAccess`, `exactOptionalPropertyTypes` (stricter, optional).

#### Declaration files
Libraries ship types as `.d.ts` files, either bundled or via DefinitelyTyped (`@types/lodash`). For untyped modules or globals, write a small `declare module` shim. Vite projects use `vite-env.d.ts` to type `import.meta.env`.

#### Workflow
- Bundlers like Vite and esbuild **strip** types without checking them. Run `tsc --noEmit` in a script and in CI.
- Use editor features: go to definition, rename symbol, quick fixes. They are the everyday payoff.
- Migrate JavaScript gradually with `allowJs` and `checkJs` if needed.

#### Good enough to move on
You can read and adjust a tsconfig, add a path alias that works in both TypeScript and Vite, type environment variables and fix a "could not find a declaration file" error properly.

Key concepts: tsconfig strict and target options, moduleResolution and jsx settings, Path aliases, Declaration files and @types, Type checking in CI with tsc --noEmit, Typing import.meta.env, Gradual migration from JavaScript.

Mini project: Set up a Vite plus TypeScript project from scratch with strict mode, an @/ alias, typed environment variables, and a CI-ready typecheck script that fails on errors.

Self-check: If Vite builds your app successfully, why can it still contain type errors?

Resources:
- [TSConfig Reference](https://www.typescriptlang.org/tsconfig/) (TypeScript)
- [Declaration Files](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html) (TypeScript)
- [Vite TypeScript features](https://vite.dev/guide/features#typescript) (Vite)

## Components and Choosing a UI Framework

Why frameworks exist, the ideas they share, and one framework to learn well (React recommended).

### Declarative UI and Component Thinking

core · beginner · about 3 h · https://www.internhack.in/roadmaps/tracks/frontend/component-thinking

The shared mental model behind React, Vue, Angular and Svelte: UI as a function of state, split into reusable components.

Building anything non-trivial with raw DOM calls gets painful: you must remember to update every element whenever data changes, and bugs appear when the screen and the data disagree. UI frameworks fix this with one idea: **describe what the UI should look like for a given state, and let the framework update the DOM**.

#### The shared concepts
- **Components**: self-contained pieces of UI (a `SearchBar`, a `ProductCard`) with their own markup, styles and behaviour, composed into trees.
- **Props / inputs**: data passed down from parent to child. Children should not mutate them.
- **State**: data a component owns that changes over time. When it changes, the component re-renders.
- **Events up, data down**: children notify parents through callbacks or emitted events; parents own the shared state.
- **Reactivity**: the mechanism that notices state changes (virtual DOM diffing in React, signals and proxies in Vue, Svelte and Angular).
- **Lifecycle and effects**: code that runs when a component appears, updates or disappears.

#### Thinking in components
Start from a mockup. Draw boxes around each piece, name them, decide which component owns each piece of state (the closest common parent of everything that needs it), and pass the rest down as props. Keep state minimal: derive values like totals or filtered lists instead of storing them.

#### Pitfalls
Duplicated state that can drift apart, components that do too much, and deep prop chains that suggest a missing abstraction.

#### Good enough to move on
Given a mockup, you can sketch a component tree, say where each piece of state lives and which props and callbacks flow between components, independent of any framework.

Key concepts: Declarative vs imperative UI, Components and composition, Props and one-way data flow, State and re-rendering, Lifting state up, Derived state, Virtual DOM vs signals.

Mini project: Take a real product page (an e-commerce listing or a chat app), draw its component tree on paper, mark where each piece of state lives, then build a small part of it in vanilla JavaScript with a render(state) function.

Self-check: Two sibling components both need the same selected item. Where should that state live, and why?

Resources:
- [Thinking in React](https://react.dev/learn/thinking-in-react) (react.dev)
- [Introduction to client-side frameworks](https://developer.mozilla.org/en-US/docs/Learn_web_development/Core/Frameworks_libraries) (MDN)

### React

recommended · intermediate · about 14 h · https://www.internhack.in/roadmaps/tracks/frontend/react

The most widely used UI library: JSX, components, props, state and events. Our recommended framework for your first job.

React is a library for building user interfaces from components written as JavaScript functions that return **JSX**. It has the largest job market, ecosystem and community of any frontend framework, which is why we recommend it as your main framework.

#### The core API
- **JSX**: HTML-like syntax that compiles to function calls. Use `className`, curly braces for expressions, and `map` to render lists (each item needs a stable `key`).
- **Components**: `function ProductCard({ product }) { return <article>...</article>; }`. Names start with a capital letter.
- **Props**: read-only inputs. Pass callbacks like `onSelect` for children to report events.
- **State** with `useState`: `const [count, setCount] = useState(0)`. Calling the setter schedules a re-render with the new value.
- **Events**: `onClick`, `onChange`, `onSubmit` receive synthetic events similar to DOM events.
- **Conditional rendering**: `&&`, ternaries, or early returns.
- **Controlled inputs**: `value` plus `onChange` keep form fields in sync with state.

#### Getting started
Scaffold with Vite (`npm create vite@latest`, React plus TypeScript template) to learn the library itself, or with a framework such as Next.js later. Install React DevTools to inspect components and props.

#### Pitfalls
- Mutating state (`items.push(x)`) instead of creating new arrays and objects.
- Using the array index as `key` for lists that reorder.
- Expecting state to update immediately after calling the setter; it applies on the next render.

#### Good enough to move on
You can build a multi-component app (a to-do list with filters, or a product catalogue with a cart) using props, state, events, lists and controlled inputs, typed with TypeScript.

Key concepts: JSX syntax and expressions, Function components and props, useState and updating state immutably, Handling events, Conditional rendering, Rendering lists and keys, Controlled form inputs, Children and composition, React DevTools, React with TypeScript.

Mini project: Build a product catalogue with search, category filters and a cart sidebar in React plus TypeScript, with state for the cart lifted to the top-level component.

Self-check: Why does `cart.push(item); setCart(cart)` fail to re-render, and what should you write instead?

Resources:
- [Learn React (Quick Start)](https://react.dev/learn) (react.dev)
- [React Reference](https://react.dev/reference/react) (react.dev)
- [Front End Development Libraries](https://www.freecodecamp.org/learn) (freeCodeCamp)

### Vue

alternative · intermediate · about 12 h · https://www.internhack.in/roadmaps/tracks/frontend/vue

A progressive framework with single-file components and fine-grained reactivity; approachable and popular in Asia and Europe.

Vue is a progressive framework: you can sprinkle it onto a page or build a full single-page app. Its **single-file components** (`.vue` files) keep template, script and styles together, and its templates look like enhanced HTML, which many people find gentler than JSX.

#### Core concepts
- **Composition API** with `<script setup>`: the modern way to write components.
- **Reactivity**: `ref()` for single values (read with `.value` in script, unwrapped in templates) and `reactive()` for objects. Vue tracks what each component reads and re-renders only what changed.
- **computed()** for derived values and **watch()** for side effects when data changes.
- **Template directives**: `v-if`, `v-for` (with `:key`), `v-bind` (`:`), `v-on` (`@`) and `v-model` for two-way form binding.
- **Props and emits**: `defineProps` and `defineEmits`, typed with TypeScript.
- **Slots**: pass markup into child components.

#### Ecosystem
Vue Router for routing, **Pinia** for shared state, Vite (created by Vue's author) for tooling and **Nuxt** as the meta-framework.

#### Pitfalls
Destructuring a `reactive` object loses reactivity; forgetting `.value` in script code; mixing the Options API and Composition API styles inconsistently.

#### Good enough to move on
You can build the same catalogue-plus-cart app in Vue with the Composition API, Pinia for the cart and Vue Router for a product detail page.

Key concepts: Single-file components, Composition API and script setup, ref, reactive and computed, Template directives and v-model, Props, emits and slots, watch and lifecycle hooks, Pinia and Vue Router.

Mini project: Build a kanban board in Vue with draggable cards, a Pinia store persisted to localStorage and computed per-column counts.

Self-check: Why does `const { count } = reactive({ count: 0 })` stop updating the UI, and how do toRefs or ref fix it?

Resources:
- [Vue.js Guide](https://vuejs.org/guide/introduction.html) (Vue)
- [Pinia](https://pinia.vuejs.org/) (Pinia)

### Angular

alternative · intermediate · about 16 h · https://www.internhack.in/roadmaps/tracks/frontend/angular

A batteries-included framework from Google with TypeScript, dependency injection and signals; common in enterprises.

Angular is a full framework rather than a library: routing, forms, HTTP, testing and a CLI come in the box, with strong conventions. It is TypeScript-first and popular in large enterprises, banks and government projects where consistency across big teams matters.

#### Core concepts
- **Standalone components**: a TypeScript class with a `@Component` decorator, a template and styles. Modern Angular no longer requires NgModules for most apps.
- **Signals**: `signal()`, `computed()` and `effect()` provide fine-grained reactivity and are now the recommended way to manage component state.
- **Template syntax**: property binding `[value]`, event binding `(click)`, and built-in control flow `@if`, `@for` (with `track`) and `@switch`.
- **Dependency injection**: services (`@Injectable`) are provided and injected with `inject()`, which makes sharing logic and testing straightforward.
- **Inputs and outputs**: `input()` and `output()` for parent-child communication.
- **Built-in modules**: the Router, HttpClient and Reactive Forms.
- **RxJS**: observables still appear in HttpClient and many libraries; learn the basics (`pipe`, `map`, `switchMap`).

#### Pitfalls
Learning from outdated tutorials (NgModules, zone-based change detection everywhere); overusing RxJS where a signal would do; ignoring the CLI's generators and conventions.

#### Good enough to move on
You can generate an app with the Angular CLI, build routed standalone components using signals, fetch data through an injected service with HttpClient and validate a Reactive Form.

Key concepts: Angular CLI and project structure, Standalone components and templates, Signals and computed, Built-in control flow, Services and dependency injection, Router and HttpClient, Reactive Forms, RxJS basics.

Mini project: Build an employee directory in Angular: a routed list and detail view, a service that loads data with HttpClient, signals for filters and a Reactive Form to add employees.

Self-check: What problem does dependency injection solve when two components need the same data-loading logic?

Resources:
- [Angular Documentation](https://angular.dev/overview) (Angular)
- [Angular Tutorials](https://angular.dev/tutorials) (Angular)

### Svelte

alternative · intermediate · about 10 h · https://www.internhack.in/roadmaps/tracks/frontend/svelte

A compiler-based framework with runes for reactivity and very little boilerplate; small bundles and a joyful developer experience.

Svelte moves most framework work to **compile time**. Instead of shipping a runtime that diffs a virtual DOM, the compiler turns your components into small JavaScript that updates the DOM directly. Components read almost like plain HTML, CSS and JavaScript.

#### Core concepts (Svelte 5)
- **Components** live in `.svelte` files with a `<script>`, markup and a scoped `<style>` block.
- **Runes** make reactivity explicit: `$state()` for reactive values, `$derived()` for computed values, `$effect()` for side effects and `$props()` for inputs.
- **Template blocks**: `{#if}`, `{#each items as item (item.id)}`, `{#await}` for promises.
- **Event handling** with attributes like `onclick={handler}`, and `bind:value` for two-way form binding.
- **Snippets** (`{#snippet}` and `{@render}`) for passing reusable markup.
- **Built-in transitions and animations** such as `transition:fade`.

#### Ecosystem
**SvelteKit** is the official app framework for routing, data loading and SSR. The ecosystem and job market are smaller than React's but growing, and the ideas transfer well.

#### Pitfalls
Many tutorials show Svelte 4 syntax (`let` reactivity and `$:` labels); learn runes. Deeply nested state and effects that write to state they read can still cause loops.

#### Good enough to move on
You can build a small app (a habit tracker or quiz) with runes, component props, each-blocks and a transition, and explain what the Svelte compiler does differently from React.

Key concepts: Svelte components and scoped styles, Runes: $state, $derived, $effect, $props and component communication, Template blocks: if, each, await, Bindings, Snippets, Transitions and animations.

Mini project: Build a quiz app in Svelte with a timer ($effect), a score ($derived), animated transitions between questions and questions loaded with an await block.

Self-check: Why can Svelte ship less JavaScript than a virtual DOM library for the same component?

Resources:
- [Svelte Interactive Tutorial](https://svelte.dev/tutorial) (Svelte)
- [Svelte Documentation](https://svelte.dev/docs) (Svelte)

## React in Depth

The parts of React that separate juniors from confident engineers: hooks, effects, context, rendering and modern concurrent features.

### Hooks, Refs and State Patterns

core · intermediate · about 6 h · https://www.internhack.in/roadmaps/tracks/frontend/react-hooks

useState, useReducer, useRef and custom hooks, plus the rules that keep hooks working correctly.

Hooks are how function components remember things and reuse logic. They look like ordinary function calls, but React tracks them **by call order**, which is why the rules of hooks exist.

#### The rules
1. Call hooks only at the top level of a component or custom hook, never inside conditions, loops or after an early return.
2. Call them only from React functions. The `eslint-plugin-react-hooks` rules enforce both; keep them on.

#### State hooks
- `useState` for independent values. Use the **updater form** `setCount(c => c + 1)` when the next value depends on the previous one.
- `useReducer` when several values change together or transitions have names (`dispatch({ type: "added", item })`). A reducer is a pure function, easy to test.
- Model state carefully: avoid redundant or contradictory state. A `status: "idle" | "loading" | "error"` beats three booleans.

#### Refs
`useRef` holds a mutable value that survives renders **without** causing re-renders. Use it for DOM nodes (focusing an input, measuring size), timers and the latest value of something. Do not read or write refs during rendering for things that affect output.

#### Custom hooks
Extract reusable stateful logic into functions named `useSomething`: `useDebounce`, `useLocalStorage`, `useMediaQuery`. Each component that calls a custom hook gets its own independent state.

#### Good enough to move on
You can refactor tangled `useState` calls into a reducer, focus an input with a ref, and write and reuse two custom hooks of your own.

Key concepts: Rules of hooks, useState updater functions, useReducer, Structuring state to avoid contradictions, useRef for DOM access and mutable values, Custom hooks, useId and other utility hooks.

Mini project: Build a multi-step checkout form driven by useReducer, with a custom useLocalStorage hook to persist progress and a ref that focuses the first invalid field on submit.

Self-check: Why does calling `setCount(count + 1)` three times in one click handler only increase count by one?

Resources:
- [Managing State](https://react.dev/learn/managing-state) (react.dev)
- [Reusing Logic with Custom Hooks](https://react.dev/learn/reusing-logic-with-custom-hooks) (react.dev)
- [Referencing Values with Refs](https://react.dev/learn/referencing-values-with-refs) (react.dev)

### Effects and Synchronisation

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/frontend/react-effects

Use useEffect to sync with systems outside React, and learn when you do not need an effect at all.

`useEffect` is the most misused hook. Its real purpose is narrow: **synchronise a component with something outside React** such as a subscription, a timer, a browser API, a third-party widget or a network connection.

#### How effects work
- The effect runs **after** React commits the render to the screen.
- The **dependency array** lists every reactive value the effect uses. React re-runs the effect when any of them changes. The lint rule tells you what is missing; do not silence it.
- The **cleanup function** you return runs before the next run and on unmount: unsubscribe, clear timers, abort fetches.
- In development with Strict Mode, React mounts, unmounts and remounts components once to expose missing cleanup. If that breaks your code, your cleanup is wrong.

#### You might not need an effect
- **Derived data**: compute it during render (`const visible = items.filter(...)`) instead of syncing a second state with an effect.
- **Responding to events**: put logic in the event handler, not in an effect that watches state.
- **Resetting state when a prop changes**: give the component a `key`.
- **Fetching data**: prefer a data library (TanStack Query) or your framework's loaders. Hand-written fetch effects need abort handling and race-condition protection.

#### Pitfalls
Infinite loops from setting state the effect depends on; objects and functions in dependencies that change every render; stale closures from missing dependencies.

#### Good enough to move on
You can write an effect with correct dependencies and cleanup (for example a WebSocket or resize listener), and you can spot and remove unnecessary effects in existing code.

Key concepts: When effects run, Dependency arrays, Cleanup functions, Strict Mode double invocation, Removing unnecessary effects, Race conditions and AbortController, useLayoutEffect, useSyncExternalStore.

Mini project: Build a live search box that fetches results as you type with debouncing, cancels stale requests with AbortController, and subscribes to online/offline events with proper cleanup.

Self-check: A component copies a prop into state with an effect so it can show a filtered list. What is the simpler, bug-free alternative?

Resources:
- [Synchronizing with Effects](https://react.dev/learn/synchronizing-with-effects) (react.dev)
- [You Might Not Need an Effect](https://react.dev/learn/you-might-not-need-an-effect) (react.dev)
- [Lifecycle of Reactive Effects](https://react.dev/learn/lifecycle-of-reactive-effects) (react.dev)

### Context and Component Composition

core · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/frontend/react-context

Share data without prop drilling using context, and design flexible components with children, slots and compound patterns.

Passing props through five layers of components that do not use them (**prop drilling**) is a sign you need either better composition or context.

#### Try composition first
Often you can avoid drilling by passing **components as children**. Instead of `<Layout user={user}>` passing `user` down to a deep `Avatar`, render `<Layout sidebar={<Avatar user={user} />}>`. The parent that has the data renders the component that needs it.

#### Context
`createContext` plus a `Provider` makes a value available to every component beneath it, read with `useContext` (or `use` in React 19). Good uses: theme, current user, locale, feature flags, and state shared by a compound component.

A typical pattern is a custom provider and hook:
```
const AuthContext = createContext<Auth | null>(null);
export function useAuth() { const v = useContext(AuthContext); if (!v) throw new Error("useAuth outside AuthProvider"); return v; }
```

#### Performance notes
Every consumer re-renders when the context value changes. Keep providers close to where they are needed, split unrelated values into separate contexts, and memoise object values. For frequently changing global state, a store library (Zustand) is usually better.

#### Composition patterns
- **Compound components**: `<Tabs>`, `<Tabs.List>`, `<Tabs.Panel>` sharing state through context.
- **Render props and slots**: pass functions or elements for customisable parts.
- **Controlled vs uncontrolled components**: let callers own state (`value` plus `onChange`) or keep it internal with a default.

#### Good enough to move on
You can build a theme or auth provider with a safe custom hook and a small compound component, and you can explain when context is the wrong tool.

Key concepts: Prop drilling and when it hurts, Composition with children and slots, createContext, Provider and useContext, Custom provider hooks, Context re-render behaviour, Compound components, Controlled vs uncontrolled components.

Mini project: Build an accessible Tabs compound component (Tabs, Tabs.List, Tabs.Trigger, Tabs.Panel) that works both controlled and uncontrolled, plus a ThemeProvider with a useTheme hook.

Self-check: Why does putting a rapidly changing value (like mouse position) in a top-level context hurt performance?

Resources:
- [Passing Data Deeply with Context](https://react.dev/learn/passing-data-deeply-with-context) (react.dev)
- [Scaling Up with Reducer and Context](https://react.dev/learn/scaling-up-with-reducer-and-context) (react.dev)

### Rendering, Reconciliation and Memoisation

core · advanced · about 5 h · https://www.internhack.in/roadmaps/tracks/frontend/react-rendering

What triggers a re-render, how React reconciles the tree, keys and identity, and when memo, useMemo, useCallback or the React Compiler help.

To fix slow or buggy React code you need a clear model of rendering. **Rendering** means React calls your component function to get new JSX; **committing** means applying the minimal DOM changes. Renders are usually cheap; unnecessary DOM work and heavy computations are what hurt.

#### What triggers a render
- The component's state changes.
- Its parent re-renders (children re-render by default, even with identical props).
- A context it consumes changes.

#### Reconciliation and identity
React compares the new tree with the previous one by **position and type**. Same type at the same position keeps its state; a different type resets it. **Keys** give list items a stable identity so reordering does not scramble state. Changing a `key` on purpose is a clean way to reset a component.

Never define a component inside another component: it becomes a new type every render and loses its state.

#### Memoisation tools
- `memo(Component)` skips re-rendering when props are shallowly equal.
- `useMemo` caches an expensive computed value; `useCallback` caches a function identity (useful when passed to memoised children or used as a dependency).
- The **React Compiler** can apply this memoisation automatically at build time, reducing manual `useMemo`/`useCallback` in codebases that adopt it.

#### How to optimise
Measure first with the React DevTools **Profiler** ("highlight updates when components render"). Common real fixes: move state down closer to where it is used, lift expensive children out as `children`, virtualise long lists, and avoid creating new objects in props for memoised children.

#### Good enough to move on
You can explain why a component re-rendered, use the Profiler to find a slow render, and fix it with the right tool rather than wrapping everything in `memo`.

Key concepts: Render and commit phases, What triggers re-renders, Reconciliation, position and type, Keys and resetting state, memo, useMemo and useCallback, React DevTools Profiler, React Compiler, List virtualisation.

Mini project: Build a data grid with 5,000 rows, filtering and a live-typing search box. Profile it, then make typing smooth by moving state down, memoising rows and virtualising the list; record before/after timings.

Self-check: Why does wrapping a child in memo not help if the parent passes `style={{ color: "red" }}` to it?

Resources:
- [Render and Commit](https://react.dev/learn/render-and-commit) (react.dev)
- [Preserving and Resetting State](https://react.dev/learn/preserving-and-resetting-state) (react.dev)
- [useMemo](https://react.dev/reference/react/useMemo) (react.dev)
- [React Compiler](https://react.dev/learn/react-compiler) (react.dev)

### Suspense, Error Boundaries and Concurrent Features

recommended · advanced · about 4 h · https://www.internhack.in/roadmaps/tracks/frontend/react-suspense

Declarative loading and error states with Suspense and error boundaries, lazy loading, and transitions for responsive UIs.

Modern React lets you describe loading and error states declaratively around parts of the tree rather than scattering `isLoading` checks everywhere.

#### Suspense
`<Suspense fallback={<Spinner />}>` shows the fallback while anything inside is **suspended**: waiting on lazily loaded code (`React.lazy`), data from a Suspense-enabled library or framework, or a promise read with `use`. Place boundaries where a loading state makes sense to the user (a panel, a route), not around every component. Nested boundaries let a page reveal progressively.

#### Error boundaries
An error boundary catches render errors in its subtree and shows a fallback instead of a blank screen. They are class components under the hood; most apps use the `react-error-boundary` package or their framework's error files. They do not catch errors in event handlers or async code; handle those yourself.

#### Transitions
- `useTransition` marks a state update as non-urgent, so typing stays responsive while a heavy tab or list re-renders. You get an `isPending` flag for subtle feedback.
- `useDeferredValue` lets an expensive child lag behind a fast-changing value like a search input.
- Transitions also stop already-visible content from being replaced by a Suspense fallback during navigation.

#### React 19 additions
Actions and `useActionState` for form submissions, `useOptimistic` for instant UI feedback, and `use` for reading promises and context.

#### Good enough to move on
You can code-split a route with `lazy` and Suspense, wrap a widget in an error boundary with a retry button and keep a filter input responsive with `useTransition`.

Key concepts: Suspense boundaries and fallbacks, React.lazy code splitting, Error boundaries, useTransition, useDeferredValue, use, Actions and useActionState, useOptimistic.

Mini project: Build a dashboard where each widget loads independently behind its own Suspense boundary and error boundary (with retry), routes are lazy-loaded, and a heavy chart filter uses useTransition.

Self-check: Why does an error thrown inside an onClick handler not get caught by an error boundary?

Resources:
- [Suspense](https://react.dev/reference/react/Suspense) (react.dev)
- [useTransition](https://react.dev/reference/react/useTransition) (react.dev)
- [lazy](https://react.dev/reference/react/lazy) (react.dev)

### React Server Components and Server Actions

recommended · advanced · about 6 h · https://www.internhack.in/roadmaps/tracks/frontend/react-server-components

Components that render on the server with direct data access and zero client JavaScript, combined with interactive client components.

**React Server Components (RSC)** split your tree into two kinds of components. Server Components run only on the server (at build time or per request); they can be `async`, read databases or files directly, keep secrets on the server and send **no JavaScript** to the browser. Client Components, marked with `"use client"` at the top of a file, are the familiar interactive components with state and effects.

You use RSC through a framework, most commonly the Next.js App Router.

#### The mental model
- Components are Server Components by default. Add `"use client"` only at the boundary where interactivity starts (a button, a form, a chart).
- Server Components can render Client Components and pass them **serialisable** props (plain data, not functions or class instances).
- Client Components cannot import Server Components, but can receive them as `children`.
- Keep the client boundary low in the tree so most of the page ships as HTML.

#### Server Actions
Functions marked `"use server"` can be called from forms or client code; the framework turns them into secure POST endpoints. Treat them like public API routes: **validate input and check authorisation** inside every action.

#### Benefits and trade-offs
Smaller bundles, no client-side fetch waterfalls for initial data, and secrets that never reach the browser. The cost is a new mental model, caching behaviour to understand, and libraries that rely on client-only APIs needing a client wrapper.

#### Good enough to move on
You can build a page that fetches data in an async Server Component, adds interactivity through a small Client Component, and mutates data with a validated Server Action.

Key concepts: Server vs Client Components, The use client boundary, Async components and server data access, Serialisable props and passing children, Server Actions and use server, Validating and authorising actions, Streaming with Suspense.

Mini project: In a Next.js App Router project, build a notes app where the list is an async Server Component reading from a database, a search box is a Client Component, and create/delete use validated Server Actions.

Self-check: Why can you not pass an onClick function prop from a Server Component to a Client Component?

Resources:
- [Server Components](https://react.dev/reference/rsc/server-components) (react.dev)
- [Server Functions](https://react.dev/reference/rsc/server-functions) (react.dev)
- ['use client' directive](https://react.dev/reference/rsc/use-client) (react.dev)

## Routing, State and Data

Turn components into a real application: URLs, where state lives, talking to APIs with caching, and validated forms.

### Client-Side Routing

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/frontend/client-routing

Map URLs to screens with React Router or TanStack Router: nested layouts, params, navigation and protected routes.

A single-page application (SPA) loads one HTML page and swaps screens in JavaScript. A **router** keeps the URL in sync with what is on screen so that links, the back button, bookmarks and sharing all work as users expect.

#### Core ideas
- **Route definitions** map paths to components: `/`, `/products`, `/products/:id`.
- **Nested routes and layouts**: a shared shell (navbar, sidebar) renders an `<Outlet />` where child routes appear.
- **Dynamic params** (`:id`) and **search params** (`?page=2&sort=price`). Put shareable UI state such as filters, tabs and pagination in the URL, not only in component state.
- **Navigation**: `<Link>` for normal navigation (it renders a real anchor, so it is accessible), `navigate()` after actions like login.
- **Loaders and actions** (React Router data APIs, TanStack Router) fetch data before a route renders, avoiding waterfalls.
- **Not found and error routes**, plus **protected routes** that redirect unauthenticated users.
- **Code splitting per route** with lazy loading.

#### Choosing a router
**React Router** is the long-standing default and doubles as a framework (the successor to Remix). **TanStack Router** offers fully type-safe routes and search params. Meta-frameworks like Next.js use **file-based routing** instead, where folders define routes.

#### Pitfalls
Using `<div onClick>` instead of links; losing scroll position or focus on navigation (move focus to the new page heading for screen reader users); forgetting to configure the host to serve `index.html` for all paths, which makes refreshes 404.

#### Good enough to move on
You can build an app with a shared layout, a list page whose filters live in search params, a detail page using a route param, a protected settings area and a 404 page.

Key concepts: Route definitions and nested layouts, Route params and search params, Link and programmatic navigation, Protected routes and redirects, Loaders and data routers, Route-based code splitting, React Router, TanStack Router, Focus and scroll management.

Mini project: Add routing to your product catalogue: layout with navbar, /products with filters and page number stored in search params, /products/:id detail, a login-protected /account area and a custom 404.

Self-check: Why should a product list's active filters live in the URL rather than only in useState?

Resources:
- [React Router](https://reactrouter.com/) (React Router)
- [TanStack Router](https://tanstack.com/router/latest) (TanStack)
- [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API) (MDN)

### State Management Principles

core · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/frontend/state-management

Classify state (local, shared, global, URL, server, form) and put each kind in the right place before reaching for a library.

"Which state library should I use?" is usually the wrong first question. Most state problems come from putting data in the wrong place. Start by classifying it.

#### Kinds of state
- **Local UI state**: is this dropdown open? Keep it in the component with `useState`.
- **Shared state**: a few nearby components need it. Lift it to their closest common parent.
- **Global client state**: theme, auth session, a shopping cart, a sidebar toggle used across the app. Context or a small store.
- **URL state**: filters, search terms, the selected tab, pagination. Use the router.
- **Server state**: data that lives in a database and is cached in the browser (products, users, messages). It can go stale and needs refetching; use a server-state library such as TanStack Query.
- **Form state**: in-progress input values, validation errors and touched fields. Use a form library for anything non-trivial.

#### Principles
- Keep state **as local as possible** and lift only when needed.
- Keep a **single source of truth**; derive everything else during render.
- Do not copy server data into a global store "just in case". That creates two sources of truth and stale bugs.
- Prefer **immutable updates** so changes are predictable and debuggable.

#### When a store library helps
When many distant components read and update the same client state, when updates are frequent (context would re-render too much), or when you want devtools, persistence and middleware.

#### Good enough to move on
You can look at an app's features and state which kind of state each piece is and where it should live, and justify why server data should not sit in a hand-rolled global store.

Key concepts: Local vs shared vs global state, URL as state, Server state vs client state, Form state, Single source of truth and derived state, Immutable updates.

Mini project: Audit a React app you built earlier: list every piece of state, label its kind, then refactor at least three pieces into a better home (URL, lifted state or a derived value) and note the bugs this removes.

Self-check: Why is storing a fetched product list in a global store and also in component state a recipe for stale data?

Resources:
- [Choosing the State Structure](https://react.dev/learn/choosing-the-state-structure) (react.dev)
- [Sharing State Between Components](https://react.dev/learn/sharing-state-between-components) (react.dev)

### Client State Libraries: Zustand, Redux Toolkit and Jotai

recommended · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/frontend/state-libraries

Use a store library when global client state outgrows context: Zustand for simplicity, Redux Toolkit for large teams, Jotai for atoms.

Once you know what is truly global client state, a small library can manage it with less boilerplate and better performance than context.

#### Zustand (our default)
A tiny store created with a hook: `const useCart = create((set) => ({ items: [], add: (i) => set((s) => ({ items: [...s.items, i] })) }))`. Components subscribe with **selectors** (`useCart(s => s.items.length)`) and re-render only when the selected slice changes. Middleware adds persistence (`persist`) and devtools. Minimal API, no providers.

#### Redux Toolkit
The modern, official way to write Redux. `createSlice` generates reducers and actions (with Immer letting you write "mutating" code safely), `configureStore` sets up devtools, and **RTK Query** handles server data. Redux shines in large apps and teams that value strict patterns, time-travel debugging and a single, predictable event log. Many existing codebases use it, so you should be able to read it.

#### Jotai
State as **atoms**: small independent pieces (`const countAtom = atom(0)`) combined into derived atoms. It fits apps with lots of fine-grained, interdependent state such as editors and canvases.

#### Others you may meet
MobX (observable, mutable style), Valtio (proxy state) and XState (state machines for complex flows, optional but powerful).

#### Pitfalls
Selecting the whole store (`useStore()`) so every change re-renders everything; putting server data in these stores instead of a server-state library; creating one giant store for unrelated concerns.

#### Good enough to move on
You can implement a persisted cart in Zustand with selectors, read and modify a Redux Toolkit slice in an existing codebase, and explain when you would reach for each tool.

Key concepts: Zustand stores and selectors, Zustand persist and devtools middleware, Redux Toolkit createSlice and configureStore, Redux DevTools, Jotai atoms and derived atoms, Selector-based re-render control, State machines with XState.

Mini project: Build a shopping cart with Zustand (persisted to localStorage, selector-based badge count), then re-implement the same slice with Redux Toolkit and compare the amount of code and the devtools experience.

Self-check: Why does `const store = useCartStore()` re-render a component more often than `useCartStore(s => s.count)`?

Resources:
- [Zustand documentation](https://zustand.docs.pmnd.rs/) (Zustand)
- [Redux Toolkit](https://redux-toolkit.js.org/) (Redux)
- [Jotai](https://jotai.org/) (Jotai)

### Server State with TanStack Query

core · intermediate · about 6 h · https://www.internhack.in/roadmaps/tracks/frontend/server-state

Cache, deduplicate, refetch and mutate server data declaratively instead of hand-writing loading and error effects.

Fetching data in `useEffect` looks easy until you need caching, deduplication, retries, background refresh, pagination, race-condition handling and keeping the UI in sync after a mutation. **TanStack Query** (formerly React Query) solves all of these and is the standard tool for server state in React apps (it also supports Vue, Svelte, Solid and Angular).

#### Queries
`useQuery({ queryKey: ["products", filters], queryFn: () => fetchProducts(filters) })` returns `data`, `isPending`, `isError` and more. The **query key** identifies cached data: components using the same key share one request and one cache entry. Change the key (for example new filters) and it fetches the new data automatically.

#### Freshness and caching
- `staleTime`: how long data counts as fresh (no refetch). The default is 0, so tune it per query.
- `gcTime`: how long unused data stays in the cache.
- Automatic refetch on window focus and reconnect keeps screens current.

#### Mutations
`useMutation` sends writes. On success, **invalidate** related queries (`queryClient.invalidateQueries({ queryKey: ["products"] })`) so they refetch, or update the cache directly. For instant feedback, apply **optimistic updates** and roll back on error.

#### More features
Pagination and infinite scrolling (`useInfiniteQuery`), dependent queries (`enabled`), prefetching on hover and the Devtools panel. Alternatives include SWR, RTK Query, Apollo for GraphQL and framework loaders.

#### Good enough to move on
You can replace hand-written fetch effects with queries and mutations, pick sensible query keys and stale times, invalidate after writes and build an infinite list.

Key concepts: useQuery and query keys, staleTime, gcTime and refetching, useMutation and invalidation, Optimistic updates, Pagination and infinite queries, Dependent and parallel queries, Prefetching, SWR and RTK Query.

Mini project: Build a GitHub repository explorer with TanStack Query: debounced search, paginated results, a detail view that prefetches on hover and an optimistic star/unstar toggle against a mock API.

Self-check: Two components on the same page call useQuery with the key ['user', 42]. How many network requests are made and why?

Resources:
- [TanStack Query Overview](https://tanstack.com/query/latest/docs/framework/react/overview) (TanStack)
- [SWR](https://swr.vercel.app/) (Vercel)

### Working with REST APIs in Production

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/frontend/api-integration

Structure an API layer with typed clients, authentication, error handling, pagination and CORS awareness.

Calling `fetch` in a component is fine for a demo. Real apps need a consistent way to talk to a backend so auth, errors and types are handled once, not in every component.

#### Build an API layer
- A small **client** module wraps fetch (or a library like `ky` or `axios`): it sets the base URL from an environment variable, adds auth headers or sends cookies with `credentials: "include"`, parses JSON and throws a typed error for non-2xx responses (remember: `fetch` does not reject on 404 or 500).
- One function per endpoint: `getProducts(params)`, `createOrder(body)`. Components and query hooks call these, never raw URLs.
- **Validate responses at the boundary** with a schema (Zod) or generate types from an **OpenAPI** spec so frontend and backend agree.

#### Everyday concerns
- **REST conventions**: resources, HTTP methods, status codes and query parameters for filtering, sorting and pagination (offset or cursor based).
- **Errors**: distinguish network failures, validation errors (show them next to fields), auth errors (redirect to login) and server errors (friendly message plus retry).
- **Auth flows**: refresh an expired session transparently once, then log out if refresh fails.
- **CORS**: the browser blocks cross-origin responses unless the server allows your origin. It is fixed on the server or with a dev proxy, never by a frontend flag.
- **Mocking**: use MSW (Mock Service Worker) to develop and test against fake endpoints before the backend is ready.

#### Good enough to move on
You have a typed API module with central error handling, environment-based base URL and auth, used through query hooks, plus mocks for local development.

Key concepts: REST resources, methods and status codes, A typed API client module, Central error handling, Auth headers, cookies and token refresh, Pagination and filtering parameters, CORS from the frontend's perspective, OpenAPI type generation, Mocking with MSW.

Mini project: Create an api/ folder for a public API (or a mock with MSW): a base client with typed errors, endpoint functions validated with Zod, a 401 handler that redirects to login, and query hooks that use them.

Self-check: Your fetch call to /api/orders returns 500 but no catch block runs. Why, and where should you fix it?

Resources:
- [Using the Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) (MDN)
- [Cross-Origin Resource Sharing (CORS)](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS) (MDN)
- [Mock Service Worker](https://mswjs.io/docs/) (MSW)

### GraphQL on the Frontend

optional · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/frontend/graphql-clients

Query exactly the data a screen needs with GraphQL, using clients like Apollo, urql or TanStack Query with codegen.

GraphQL is an API style where the client sends a **query** describing the exact fields it wants, and the server returns JSON in that shape from a single endpoint. It is popular at companies with many clients (web, mobile) sharing one API, and with platforms like GitHub and Shopify.

#### Concepts
- **Schema**: the typed contract of types, fields and relations the server exposes.
- **Queries** read data, **mutations** change it, **subscriptions** stream updates.
- **Variables** keep queries static and reusable: `query Product($id: ID!) { product(id: $id) { name price } }`.
- **Fragments** let components declare the fields they need, colocated with the component.

#### Clients
- **Apollo Client**: full-featured with a normalised cache that updates every screen showing an entity after a mutation.
- **urql**: lighter and extensible.
- **Relay**: highly optimised and opinionated, used at Meta scale.
- A plain fetch or **TanStack Query** with `graphql-request` works well for simple needs.

#### Type safety
Use **GraphQL Code Generator** (or gql.tada) to generate TypeScript types from the schema and your queries, so a renamed field breaks the build rather than production.

#### Pitfalls
Over-fetching through huge shared queries; cache normalisation surprises when objects lack an `id`; errors that arrive with HTTP 200 inside an `errors` array, which you must check.

#### Good enough to move on
You can write queries with variables and fragments, run them from React with one client, generate types and update the cache after a mutation.

Key concepts: Schema, types and fields, Queries, mutations and variables, Fragments and colocation, Apollo Client, urql and Relay, GraphQL Code Generator, Normalised caching.

Mini project: Build a small GitHub profile viewer with the GitHub GraphQL API: typed queries via codegen, fragments per component and a mutation that stars a repository and updates the cache.

Self-check: A GraphQL response has status 200 but the UI shows nothing. What should your client code check?

Resources:
- [Learn GraphQL](https://graphql.org/learn/) (GraphQL Foundation)
- [Apollo Client documentation](https://www.apollographql.com/docs/react/) (Apollo)
- [GraphQL Code Generator](https://the-guild.dev/graphql/codegen) (The Guild)

### Forms in React with React Hook Form

core · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/frontend/react-forms

Build performant, accessible forms with React Hook Form: registration, validation, errors, arrays and submission states.

Forms are where users give you money and data, so they deserve care. Handling every field with `useState` gets verbose and re-renders on every keystroke. **React Hook Form** (RHF) keeps inputs mostly uncontrolled, re-renders only what needs it and gives you a tidy API for validation and errors.

#### The basics
- `const { register, handleSubmit, formState: { errors, isSubmitting } } = useForm<FormValues>()`.
- `<input {...register("email", { required: "Email is required" })} />` wires up a field.
- `handleSubmit(onSubmit)` validates, then calls your function with typed values.
- `Controller` or `useController` integrates controlled components such as date pickers and custom selects.
- `useFieldArray` handles repeating groups (multiple addresses, line items).
- Pair it with a **schema resolver** (Zod) so validation rules live in one typed place.

#### UX that matters
- Label every input with `<label>`; do not rely on placeholders.
- Validate on blur or submit, not on every keystroke from the first character.
- Show errors next to the field, connect them with `aria-describedby` and set `aria-invalid`.
- Move focus to the first invalid field on submit (RHF does this by default).
- Disable double submits, show progress, and keep the user's input after a server error.
- Map **server-side validation errors** back to fields with `setError`.

#### Alternatives
TanStack Form (type-safe, framework-agnostic), Formik (older codebases) and native forms with React 19 Actions for simple cases.

#### Good enough to move on
You can build a multi-field signup form with a dynamic field array, schema validation, accessible error messages and server error mapping.

Key concepts: useForm and register, handleSubmit and submission state, Displaying errors accessibly, Controller for custom inputs, useFieldArray, Mapping server errors with setError, TanStack Form and Formik.

Mini project: Build an invoice editor form: customer details, a dynamic list of line items with computed totals, a custom date picker via Controller and server-side error mapping from a mock API.

Self-check: Why does React Hook Form re-render less than a form built from one useState per field?

Resources:
- [React Hook Form Get Started](https://react-hook-form.com/get-started) (React Hook Form)
- [TanStack Form](https://tanstack.com/form/latest) (TanStack)
- [Forms tutorial](https://www.w3.org/WAI/tutorials/forms/) (W3C WAI)

### Schema Validation with Zod

core · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/frontend/schema-validation

Define data shapes once with Zod to validate forms and API responses at runtime and infer TypeScript types from the same schema.

TypeScript types vanish at runtime, so they cannot protect you from a user typing nonsense or an API returning an unexpected shape. A **schema library** checks real data at runtime, and with Zod you also infer the static type from the schema so the two never drift apart.

#### Zod basics
```
const Signup = z.object({ email: z.email(), age: z.number().int().min(18), plan: z.enum(["free", "pro"]) });
type Signup = z.infer<typeof Signup>;
```
- `schema.parse(data)` returns typed data or throws; `safeParse` returns a result object you can branch on.
- Refinements (`.refine`, `.superRefine`) for cross-field rules like "passwords match".
- Transforms and coercion (`z.coerce.number()`) to turn form strings into numbers or dates.
- Compose schemas with `.extend`, `.pick`, `.omit` and `.partial` just like utility types.

#### Where to use it
- **Forms**: plug the schema into React Hook Form with `zodResolver`; error messages come from the schema.
- **API boundaries**: validate responses in your API client so bad data fails loudly in one place.
- **Environment variables**: validate `import.meta.env` at startup.
- **Shared contracts**: in full-stack TypeScript apps, the same schema validates on the server (Server Actions, API routes) and the client.

Alternatives with similar ideas include Valibot (smaller bundles), ArkType and Yup (common in older code).

#### Pitfalls
Client-side validation is for UX only; the **server must validate again**. Keep error messages human, and avoid huge schemas in the client bundle when a smaller library would do.

#### Good enough to move on
You can write a schema with refinements and transforms, infer its type, use it in a form and in an API client, and explain why the server still validates.

Key concepts: Defining object schemas, parse vs safeParse, Inferring types with z.infer, Refinements for cross-field rules, Coercion and transforms, zodResolver with React Hook Form, Validating API responses and env vars, Valibot and Yup.

Mini project: Create one Zod schema for a job application (with a password-confirm refinement and coerced numeric fields), use it for the form, reuse it to validate a mock API's response, and validate your app's env vars on startup.

Self-check: If the frontend validates a form with Zod, why must the backend validate the same data again?

Resources:
- [Zod documentation](https://zod.dev/) (Zod)
- [Valibot](https://valibot.dev/) (Valibot)

## Testing Frontend Applications

Gain confidence to change code: unit tests for logic, component tests for behaviour and end-to-end tests for critical journeys.

### Testing Fundamentals with Vitest

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/frontend/testing-fundamentals

Why and what to test, the testing trophy, and writing fast unit tests with Vitest (or Jest) including mocks and coverage.

Tests let you refactor and ship without fear. The goal is not 100% coverage; it is **confidence per minute spent**. Test the behaviour users and other code rely on, not implementation details.

#### Types of tests
- **Static checks**: TypeScript and ESLint catch a whole class of bugs for free.
- **Unit tests**: pure functions and hooks such as price calculations, reducers, formatters and validators. Fast and precise.
- **Integration / component tests**: render components with their children and check behaviour from the user's perspective. For UIs these usually give the best return.
- **End-to-end tests**: a real browser runs through critical journeys like signup and checkout. Slow but the most realistic.

#### Vitest
Vitest is a fast test runner that reuses your Vite config, so TypeScript, JSX and path aliases just work. Its API matches **Jest** (`describe`, `it`/`test`, `expect`), which you will still find in many codebases.
- **Arrange, act, assert**: set up data, run the code, check the result.
- **Matchers**: `toBe`, `toEqual`, `toThrow`, `toHaveBeenCalledWith`.
- **Mocks and spies**: `vi.fn()`, `vi.spyOn()`, `vi.mock()` for modules; fake timers with `vi.useFakeTimers()`.
- **Watch mode** while coding; **coverage** reports to find untested branches.

#### Good tests
Descriptive names ("applies a 10% discount for orders over 100"), one behaviour per test, no dependence on order, and minimal mocking. If a refactor that keeps behaviour breaks a test, the test was too coupled to implementation.

#### Good enough to move on
You can set up Vitest in a Vite project, unit test utility functions and a reducer including edge cases, mock a module and read a coverage report.

Key concepts: Why test and what to test, Unit, integration and end-to-end tests, Vitest setup and API, Jest, Matchers and assertions, Mocks, spies and fake timers, Coverage reports, Testing custom hooks.

Mini project: Add Vitest to your catalogue app and unit test the cart reducer, price formatting and discount rules, including edge cases (empty cart, negative quantities), and a debounce helper using fake timers.

Self-check: Why might a test that checks a component's internal state variable be worse than one that checks what the user sees?

Resources:
- [Vitest Guide](https://vitest.dev/guide/) (Vitest)
- [Jest Getting Started](https://jestjs.io/docs/getting-started) (Jest)

### Component Testing with Testing Library

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/frontend/component-testing

Test components the way users use them: query by role and label, simulate real interactions and mock the network with MSW.

**Testing Library** (`@testing-library/react` and friends for Vue, Svelte and Angular) renders components in a simulated DOM (jsdom or happy-dom) and encourages tests that resemble how people use your app. If your test finds a button by its accessible name, it also checks that screen reader users can find it.

#### Query priority
1. `getByRole("button", { name: /add to cart/i })` for almost everything.
2. `getByLabelText` for form fields, `getByText` for non-interactive content.
3. `getByTestId` only as a last resort.

Variants: `getBy` throws if missing, `queryBy` returns null (for asserting absence), `findBy` waits for async content.

#### Interactions
Use `@testing-library/user-event` (`await user.click(button)`, `await user.type(input, "hello")`), which simulates real keyboard and pointer sequences more faithfully than firing single events. Assert with `@testing-library/jest-dom` matchers like `toBeInTheDocument`, `toBeDisabled` and `toHaveValue`.

#### Async and network
Mock HTTP at the network level with **MSW** so components use their real fetch and query code. Wrap components in the providers they need (router, QueryClient, theme) with a custom `render` helper.

#### Other tools
- **Browser mode** in Vitest or Playwright component tests run in a real browser when jsdom is not enough.
- **Storybook** interaction and visual tests pair well with component stories.
- **Snapshot tests** are easy to write and easy to rubber-stamp; use them sparingly.

#### Good enough to move on
You can test a form that validates, submits to a mocked API and shows success and error states, using only role and label queries and user-event.

Key concepts: render and screen, Queries by role and label, getBy, queryBy and findBy, user-event interactions, jest-dom matchers, Mocking the network with MSW, Custom render with providers, Vitest browser mode.

Mini project: Write component tests for your signup form and product list: validation errors, successful submission against an MSW handler, a server error state and filtering, all without test ids.

Self-check: When should you use findByRole instead of getByRole?

Resources:
- [Testing Library](https://testing-library.com/docs/) (Testing Library)
- [Which query should I use?](https://testing-library.com/docs/queries/about) (Testing Library)
- [Mock Service Worker](https://mswjs.io/docs/) (MSW)

### End-to-End Testing with Playwright

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/frontend/e2e-testing

Automate real browsers to test critical user journeys; Playwright recommended, Cypress as the common alternative.

End-to-end (E2E) tests drive a real browser against your running app, covering routing, network, storage and third-party scripts together. They catch the bugs that slip between units, but they are slower and more brittle, so reserve them for **critical journeys**: sign up, log in, search, checkout, and anything that would page someone at 3 a.m.

#### Playwright (recommended)
- Runs Chromium, Firefox and WebKit, in parallel, headless in CI.
- **Locators** mirror Testing Library: `page.getByRole("button", { name: "Pay" })`.
- **Auto-waiting** and web-first assertions (`await expect(locator).toBeVisible()`) remove most sleeps and flakiness.
- **Codegen** records interactions into test code; the **trace viewer** shows screenshots, DOM snapshots and network for each step of a failed run.
- Network interception, multiple tabs and contexts, mobile emulation and saved auth state.

#### Cypress (alternative)
Runs inside the browser with an excellent interactive runner and time-travel debugging. Widely used in existing projects. Historically more limited with multiple tabs and cross-origin flows.

#### Writing stable E2E tests
- Seed or create test data through APIs, not by clicking through setup screens.
- Log in once and reuse storage state.
- Never use fixed timeouts; wait for observable conditions.
- Keep tests independent so they can run in parallel.
- Run them in CI against a preview deployment and keep traces on failure.

#### Good enough to move on
You can write three reliable Playwright tests for your app's critical paths, run them headless in CI across two browsers and debug a failure with the trace viewer.

Key concepts: When E2E tests are worth it, Playwright, Cypress, Locators and web-first assertions, Auth state and test data setup, Trace viewer and debugging, Running E2E in CI, Visual regression screenshots.

Mini project: Add Playwright to your project with tests for signup, search and add-to-cart-then-checkout, reuse login state across tests, and run them in GitHub Actions with traces uploaded on failure.

Self-check: Why is `await page.waitForTimeout(3000)` a bad way to wait for search results, and what should you use instead?

Resources:
- [Playwright Introduction](https://playwright.dev/docs/intro) (Playwright)
- [Playwright Best Practices](https://playwright.dev/docs/best-practices) (Playwright)
- [Cypress Documentation](https://docs.cypress.io/) (Cypress)

## Accessibility in Depth

Build interfaces that work for everyone, including keyboard, screen reader and low-vision users, and meet WCAG requirements.

### WCAG and Inclusive Design Principles

core · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/frontend/wcag

The POUR principles, WCAG 2.2 AA success criteria, colour contrast and motion, and why accessibility is a legal and product requirement.

Around one in six people lives with a disability, and everyone is temporarily impaired sometimes: a broken arm, bright sunlight, a noisy train. Accessibility (a11y) is also a legal requirement in many regions (the ADA in the US, the European Accessibility Act, and similar laws elsewhere), so companies expect frontend developers to know the standard.

#### WCAG in a nutshell
The **Web Content Accessibility Guidelines** are organised under four principles, **POUR**:
- **Perceivable**: text alternatives for images, captions for video, sufficient colour contrast, content that does not rely on colour alone.
- **Operable**: everything works with a keyboard, users have enough time, nothing flashes dangerously, clear navigation.
- **Understandable**: readable language, predictable behaviour, helpful error messages and labels.
- **Robust**: valid, semantic markup that assistive technologies can interpret.

Each guideline has testable **success criteria** at levels A, AA and AAA. **WCAG 2.2 level AA** is the usual target in contracts and law.

#### Criteria you will meet daily
- Contrast of at least 4.5:1 for normal text and 3:1 for large text and UI components.
- Visible focus indicators, and focused elements not hidden behind sticky headers.
- Target sizes large enough to tap (at least 24 by 24 CSS pixels).
- Text that can resize to 200% and reflow at narrow widths without horizontal scrolling.
- Respect `prefers-reduced-motion` for large animations.

#### Good enough to move on
You can explain POUR, check contrast with DevTools, list ten common AA criteria and include accessibility acceptance criteria when you plan a feature.

Key concepts: Why accessibility matters, POUR principles, WCAG levels A, AA and AAA, Colour contrast and use of colour, Resize, reflow and target size, Reduced motion and flashing, Accessibility laws and conformance.

Mini project: Audit a popular website against a WCAG 2.2 AA checklist of 15 criteria, record each failure with a screenshot and the relevant success criterion, and propose a fix for each.

Self-check: Light grey text (#999) on white fails WCAG AA. What contrast ratio does normal-size body text need?

Resources:
- [WCAG 2 Overview](https://www.w3.org/WAI/standards-guidelines/wcag/) (W3C WAI)
- [How to Meet WCAG (Quick Reference)](https://www.w3.org/WAI/WCAG22/quickref/) (W3C WAI)
- [Learn Accessibility](https://web.dev/learn/accessibility) (web.dev)

### ARIA and Accessible Custom Widgets

core · advanced · about 5 h · https://www.internhack.in/roadmaps/tracks/frontend/aria

When and how to use ARIA roles, states and properties, and how to build modals, menus, tabs and comboboxes that assistive tech understands.

**ARIA** (Accessible Rich Internet Applications) is a set of attributes that tell assistive technologies what a custom element is, what state it is in and how it relates to other elements. It changes the **accessibility tree** only; it adds no behaviour.

#### The first rule of ARIA
**Do not use ARIA if a native element does the job.** A `<button>` is focusable, clickable with Enter and Space and announced as a button for free. A `<div role="button">` needs `tabindex`, key handlers and more. "No ARIA is better than bad ARIA": incorrect roles actively mislead users.

#### The three parts
- **Roles**: what it is (`dialog`, `tablist`, `tab`, `menu`, `alert`, `combobox`).
- **States and properties**: `aria-expanded`, `aria-selected`, `aria-checked`, `aria-disabled`, `aria-invalid`, `aria-current="page"`.
- **Relationships and names**: `aria-labelledby`, `aria-describedby`, `aria-controls`, and `aria-label` when there is no visible label.

#### Live regions
`aria-live="polite"` or `role="status"` announce dynamic updates such as "3 results found" or "Saved"; `role="alert"` for urgent errors. The region must exist in the DOM before its content changes.

#### Common widgets
Follow the **ARIA Authoring Practices Guide (APG)** patterns for keyboard and ARIA behaviour: disclosure, dialog (modal), tabs, menu button, combobox and listbox. Prefer native `<dialog>` and `<details>` where suitable, or a headless library like **Radix** or **React Aria** that implements these patterns correctly.

#### Good enough to move on
You can explain the accessibility tree, pick native elements over ARIA, correctly build a disclosure and tabs widget following APG, and announce async results with a live region.

Key concepts: The accessibility tree, First rule of ARIA: prefer native HTML, Roles, states and properties, Accessible names and descriptions, Live regions, ARIA Authoring Practices patterns, Headless libraries: Radix, React Aria.

Mini project: Build an accessible tabs component and a menu button following the APG patterns (roles, states, arrow-key navigation), plus a search page that announces the result count with a live region.

Self-check: Why is adding role="button" to a div not enough to make it an accessible button?

Resources:
- [ARIA Authoring Practices Guide](https://www.w3.org/WAI/ARIA/apg/) (W3C WAI)
- [ARIA](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA) (MDN)

### Keyboard Navigation and Focus Management

core · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/frontend/keyboard-focus

Make every interaction work without a mouse: tab order, visible focus, skip links, focus traps in modals and focus on route changes.

Many people navigate entirely by keyboard or with switch devices and voice control that emulate one. If something cannot be reached or operated with the keyboard, it is broken for them.

#### Basics
- **Tab** and **Shift+Tab** move between interactive elements; **Enter** activates links and buttons; **Space** toggles buttons and checkboxes; **arrow keys** move within composite widgets (tabs, menus, radio groups); **Escape** closes overlays.
- Focus order should follow visual order. Rearranging with CSS (`order`, absolute positioning) can make it jump around confusingly.
- Use `tabindex="0"` to make a custom widget focusable, `tabindex="-1"` to focus something programmatically, and **never** positive tabindex values.
- Style `:focus-visible` with a clear outline; never remove outlines without a replacement.

#### Focus management in apps
- **Modals**: move focus into the dialog on open, keep it trapped inside, close on Escape and **return focus** to the trigger on close. Native `<dialog>` with `showModal()` does most of this, and the `inert` attribute disables background content.
- **Route changes in SPAs**: move focus to the new page's main heading or announce the page title, otherwise screen reader users do not know anything changed.
- **Deleting items or closing panels**: send focus somewhere sensible, not to `<body>`.
- **Skip link**: a first focusable "Skip to main content" link helps keyboard users bypass repeated navigation.
- **Roving tabindex** for toolbars and lists: one tab stop, arrow keys inside.

#### Good enough to move on
You can unplug your mouse and complete every flow in your app, with a visible focus ring, a skip link, a correct modal focus trap and focus moved on navigation.

Key concepts: Standard keyboard interactions, Logical focus order, tabindex 0 and -1, Visible focus with :focus-visible, Modal focus trapping and restoring, Focus on SPA route changes, Skip links, Roving tabindex.

Mini project: Make your app fully keyboard operable: add a skip link, visible focus styles, a modal with focus trap and restore, focus management after route changes and after deleting a list item.

Self-check: After a modal closes, where should keyboard focus go, and what happens if you do nothing?

Resources:
- [Keyboard-navigable JavaScript widgets](https://developer.mozilla.org/en-US/docs/Web/Accessibility/Guides/Keyboard-navigable_JavaScript_widgets) (MDN)
- [Focus](https://web.dev/learn/accessibility/focus) (web.dev)
- [Developing a Keyboard Interface](https://www.w3.org/WAI/ARIA/apg/practices/keyboard-interface/) (W3C WAI)

### Screen Readers and Accessibility Testing

recommended · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/frontend/a11y-testing

Test with real assistive technology and automated tools: VoiceOver, NVDA, axe, Lighthouse and accessibility linting.

You cannot know an interface is accessible until you try it the way disabled users do. Automated tools find roughly a third to a half of issues; the rest needs manual testing.

#### Automated checks
- **axe DevTools** browser extension and `@axe-core/playwright` or `vitest-axe` in tests to catch missing labels, contrast failures and invalid ARIA.
- **Lighthouse** accessibility audit for a quick overview.
- **eslint-plugin-jsx-a11y** catches problems in JSX while you type.
- Testing Library role queries already fail when elements are unnamed.

#### Manual checks
- **Keyboard only**: complete every flow.
- **Zoom** to 200% and 400% and check reflow.
- **Accessibility tree** panel in Chrome or Firefox DevTools to see roles and names.
- **Screen readers**: VoiceOver (built into macOS and iOS), NVDA (free on Windows), TalkBack (Android). Learn a handful of commands: read next item, jump by headings, list links and form controls, interact with a form.

#### What to listen for
Does every control announce a sensible name, role and state? Do headings outline the page? Are errors and dynamic updates announced? Do images have useful alternative text (or empty `alt=""` if decorative)? Is anything announced twice or not at all?

#### Make it routine
Add axe checks to component and E2E tests, include an accessibility item in your pull request checklist and do a quick screen reader pass on new features. Fixing issues while building is far cheaper than after an audit.

#### Good enough to move on
You can navigate a page with one screen reader by headings and landmarks, run axe in CI and fix the issues it reports, and explain what automated tools cannot catch.

Key concepts: axe DevTools and axe-core, Lighthouse accessibility audit, eslint-plugin-jsx-a11y, DevTools accessibility tree, VoiceOver basics, NVDA basics, Automated a11y checks in CI, Writing good alt text.

Mini project: Add axe checks to your Playwright suite for every main page, fix all violations, then record a short screen reader walkthrough of your checkout flow and fix anything confusing you hear.

Self-check: Name two accessibility problems that an automated tool like axe cannot reliably detect.

Resources:
- [axe-core](https://github.com/dequelabs/axe-core) (Deque)
- [Accessibility testing](https://web.dev/learn/accessibility/test-automated) (web.dev)
- [NVDA](https://www.nvaccess.org/) (NV Access)

## Web Performance

Measure what users experience, then make pages load fast and respond instantly on real devices and networks.

### Core Web Vitals and Performance Metrics

core · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/frontend/core-web-vitals

LCP, INP and CLS: what they measure, their thresholds, and how lab and field data differ.

Performance is a feature: slow pages lose users, sales and search ranking. Google's **Core Web Vitals** give a shared vocabulary for the parts of speed users actually feel.

#### The three Core Web Vitals
- **Largest Contentful Paint (LCP)**: when the biggest visible element (usually a hero image or heading) finishes rendering. Good: 2.5 s or less. Common causes of slowness: slow server response, render-blocking CSS and JS, a lazy-loaded or unoptimised hero image.
- **Interaction to Next Paint (INP)**: how quickly the page visually responds to clicks, taps and key presses throughout the visit. Good: 200 ms or less. Caused by long JavaScript tasks blocking the main thread.
- **Cumulative Layout Shift (CLS)**: how much content jumps around unexpectedly. Good: 0.1 or less. Caused by images without dimensions, late-loading ads or embeds, and web fonts swapping.

Supporting metrics: **TTFB** (server response time) and **FCP** (first paint of any content).

#### Lab vs field data
- **Lab data** (Lighthouse, DevTools) runs a controlled test on one machine. Great for debugging, but it is not your users.
- **Field data** (real user monitoring, the Chrome UX Report shown in PageSpeed Insights, or the `web-vitals` library sending metrics to your analytics) reflects real devices and networks. Judge success by the **75th percentile** of field data.

#### Budgets
Set a performance budget (for example LCP under 2.5 s on a mid-range phone on 4G, and under 200 KB of JavaScript for a landing page) and check it in CI so regressions are caught in review.

#### Good enough to move on
You can explain each vital, name its typical causes, read a PageSpeed Insights report and collect field metrics from your own app with the web-vitals library.

Key concepts: Largest Contentful Paint (LCP), Interaction to Next Paint (INP), Cumulative Layout Shift (CLS), TTFB and FCP, Lab vs field data, web-vitals library and RUM, Performance budgets.

Mini project: Add the web-vitals library to one of your deployed apps, log LCP, INP and CLS to the console or an analytics endpoint, and compare the numbers with a PageSpeed Insights run.

Self-check: Your Lighthouse score is 98 but field INP is poor. How can both be true?

Resources:
- [Web Vitals](https://web.dev/articles/vitals) (web.dev)
- [Learn Performance](https://web.dev/learn/performance) (web.dev)
- [PageSpeed Insights](https://pagespeed.web.dev/) (Google)

### JavaScript Loading and Runtime Performance

core · advanced · about 5 h · https://www.internhack.in/roadmaps/tracks/frontend/javascript-performance

Ship less JavaScript with code splitting and tree shaking, load scripts smartly and keep the main thread free of long tasks.

JavaScript is the most expensive resource per byte: it must be downloaded, parsed, compiled and executed on the main thread, where it competes with user input. Most slow modern sites are slow because of JavaScript.

#### Ship less
- **Analyse the bundle** (`rollup-plugin-visualizer`, `vite-bundle-visualizer`, source-map-explorer) and question every large dependency. Swap heavy libraries for lighter ones or native APIs (`Intl` instead of moment, native `fetch` instead of a big HTTP client).
- **Code splitting**: split by route and lazy-load heavy, rarely used features (rich text editors, charts, maps) with dynamic `import()`.
- **Tree shaking** works best with ES modules and named imports.
- Audit **third-party scripts** (analytics, chat widgets, tag managers); they are frequent culprits.

#### Load it well
- `<script type="module">` and `defer` do not block parsing; avoid synchronous scripts in the head.
- **Preload** critical resources and **prefetch** likely next routes.
- Serve modern syntax to modern browsers rather than transpiling everything down.

#### Keep the main thread free
- A **long task** is anything over 50 ms; it delays response to input and hurts INP.
- Break up work: yield with `scheduler.yield()` or `setTimeout`, process in chunks, or move heavy computation to a **Web Worker**.
- Debounce and throttle expensive handlers (scroll, resize, input).
- Virtualise long lists and avoid layout thrashing (reading layout then writing styles in a loop).
- In React, see the rendering topic: move state down and memoise genuinely expensive work.

#### Good enough to move on
You can find the biggest dependencies in a bundle, lazy-load a heavy route, identify long tasks in the Performance panel and break one up.

Key concepts: Cost of JavaScript, Bundle analysis, Route and component code splitting, Dynamic import(), defer, async and module scripts, Preload and prefetch, Long tasks and yielding, Third-party script management, Debounce and throttle.

Mini project: Take a React app, cut its initial JavaScript by at least 30%: analyse the bundle, replace one heavy dependency, lazy-load two routes and a heavy widget, and document before and after sizes and INP.

Self-check: Why does a 300 KB JavaScript file hurt more than a 300 KB JPEG on a mid-range phone?

Resources:
- [Reduce JavaScript payloads with code splitting](https://web.dev/articles/reduce-javascript-payloads-with-code-splitting) (web.dev)
- [Optimize long tasks](https://web.dev/articles/optimize-long-tasks) (web.dev)
- [Optimize Interaction to Next Paint](https://web.dev/articles/optimize-inp) (web.dev)

### Images, Fonts and Critical Rendering Path

core · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/frontend/asset-optimization

Serve responsive modern images, load fonts without layout shift, and prioritise the resources needed for the first paint.

Images are usually the heaviest bytes on a page, and the LCP element is an image on most sites. Fonts and CSS block text from appearing. Getting these right is often the quickest performance win.

#### Images
- Use modern formats: **AVIF** or **WebP** with fallbacks via `<picture>`.
- Serve the right size with `srcset` and `sizes` so phones do not download desktop images.
- Always set `width` and `height` (or `aspect-ratio`) to prevent layout shift.
- `loading="lazy"` for below-the-fold images, but **never** lazy-load the LCP image. Give the hero image `fetchpriority="high"`.
- Use SVG for icons and logos, and an image CDN or framework image component (Next.js `<Image>`) to automate resizing.

#### Fonts
- Prefer **WOFF2**, subset to the characters you need, and self-host or use a reliable provider.
- `font-display: swap` shows fallback text immediately; tune fallback metrics (`size-adjust`) to reduce the shift when the web font arrives.
- Preload the one or two most important font files; use fewer weights, or a variable font.
- System font stacks cost nothing.

#### Critical rendering path
- CSS is **render-blocking**: keep critical CSS small, inline it if needed, and load the rest efficiently.
- Put non-critical scripts behind `defer`.
- Use `preconnect` for important third-party origins.
- Reduce request chains: the browser should discover the LCP resource in the initial HTML, not after JavaScript runs.

#### Good enough to move on
You can turn a page with a large hero image and custom fonts into one with a fast LCP and near-zero CLS, and explain each change using the Network and Performance panels.

Key concepts: Modern image formats: AVIF and WebP, Responsive images with srcset and sizes, Lazy loading and fetchpriority, Preventing layout shift, Web font loading and font-display, Render-blocking CSS and critical CSS, preconnect and preload hints, Image CDNs and framework image components.

Mini project: Optimise a landing page: convert images to AVIF/WebP with srcset, fix the LCP image priority, add dimensions everywhere, subset and preload the main font, and bring CLS below 0.05.

Self-check: Why does adding loading="lazy" to the hero image make LCP worse?

Resources:
- [Optimize Largest Contentful Paint](https://web.dev/articles/optimize-lcp) (web.dev)
- [Responsive images](https://developer.mozilla.org/en-US/docs/Web/HTML/Guides/Responsive_images) (MDN)
- [Best practices for fonts](https://web.dev/articles/font-best-practices) (web.dev)

### HTTP Caching, Compression and CDNs

core · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/frontend/caching

Use Cache-Control, content hashing, compression and CDNs so repeat visits are near-instant and servers stay cool.

The fastest request is the one never made. HTTP caching lets browsers and CDNs reuse responses, and it is mostly configuration you set once.

#### Cache-Control essentials
- `Cache-Control: public, max-age=31536000, immutable` for **hashed static assets** (`app.3f9a1c.js`, images with hashes). They never change; a new build produces new names.
- `Cache-Control: no-cache` for **HTML**: the browser may store it but must revalidate, so users get new deployments immediately.
- `no-store` for sensitive, personalised responses.
- **Validators**: `ETag` and `Last-Modified` let the browser ask "has this changed?" and receive a tiny `304 Not Modified`.
- `stale-while-revalidate` serves a cached copy instantly while fetching a fresh one in the background.

#### CDNs
A Content Delivery Network caches your files in data centres near users, cutting latency. Hosts like Vercel, Netlify and Cloudflare include one. Understand **cache invalidation** on deploy and the difference between browser cache and edge cache (`s-maxage`).

#### Compression and protocols
Serve text assets with **Brotli** (or gzip) compression; it often shrinks JavaScript and CSS by 70% or more. HTTP/2 and HTTP/3 multiplex many requests over one connection, so bundling everything into one giant file is no longer necessary.

#### Application-level caching
Service workers (covered with PWAs) and data libraries like TanStack Query add caching layers under your control. Keep one clear owner per layer to avoid stale-data mysteries.

#### Good enough to move on
You can read the caching headers of any response in DevTools, configure long-lived caching for hashed assets and revalidation for HTML on your host, and explain why a deploy did or did not reach users.

Key concepts: Cache-Control directives, Immutable hashed assets vs HTML, ETag and 304 revalidation, stale-while-revalidate, CDNs and edge caching, Brotli and gzip compression, HTTP/2 and HTTP/3.

Mini project: Deploy a Vite build and configure headers so hashed assets are cached for a year and HTML revalidates; verify with DevTools that a second visit loads assets from cache and a new deploy is picked up.

Self-check: What would go wrong if you set max-age=31536000 on index.html?

Resources:
- [HTTP caching](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Caching) (MDN)
- [Prevent unnecessary network requests with the HTTP Cache](https://web.dev/articles/http-cache) (web.dev)

### Profiling with Lighthouse and DevTools

recommended · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/frontend/performance-tooling

Diagnose performance problems methodically with Lighthouse, the Performance and Network panels, and CPU and network throttling.

Optimising without measuring is guessing. Browser DevTools show exactly where time goes, if you know where to look.

#### Lighthouse
Run it from DevTools or PageSpeed Insights for an audit of performance, accessibility, SEO and best practices. Treat the score as a signal and read the **opportunities and diagnostics**: render-blocking resources, unused JavaScript, image sizing, LCP element. Always test in an incognito window (extensions distort results) with **mobile emulation and throttling**, because your laptop is not your users' phone. `lighthouse-ci` can run it on every pull request.

#### Network panel
Waterfall of every request: timing breakdown (DNS, connect, TTFB, download), sizes (transferred vs resource), caching status and priority. Look for long request chains, large files and missing compression. Throttle to "Fast 4G" or "Slow 4G".

#### Performance panel
Record a page load or an interaction:
- The **main thread** flame chart shows long tasks (red corners), scripting, style recalculation, layout and paint.
- **Screenshots** and the timings track show when LCP happens and which element it is.
- **Layout shifts** are highlighted with the elements that moved.
- **CPU throttling** (4x or 6x slowdown) approximates mid-range phones.
The live metrics view shows LCP, INP and CLS as you interact.

#### Framework tools
React DevTools Profiler for component render costs, and bundle analysers for what is shipped.

#### A method
Measure, form one hypothesis, change one thing, measure again. Keep notes so you know which change helped.

#### Good enough to move on
You can record a trace of a slow interaction, point to the long task and the code responsible, and explain every major item in a Lighthouse report.

Key concepts: Lighthouse audits and opportunities, Network panel waterfall, Performance panel and flame charts, CPU and network throttling, Finding long tasks and layout shifts, Lighthouse CI, Measure, change, re-measure method.

Mini project: Pick a slow interaction in one of your apps, record a Performance trace with 4x CPU throttling, identify the responsible code, fix it, and write a short before/after report with screenshots of both traces.

Self-check: Why should you run Lighthouse in an incognito window with throttling instead of a normal browser tab on your laptop?

Resources:
- [Lighthouse overview](https://developer.chrome.com/docs/lighthouse/overview) (Chrome for Developers)
- [Analyze runtime performance](https://developer.chrome.com/docs/devtools/performance) (Chrome for Developers)
- [Network features reference](https://developer.chrome.com/docs/devtools/network) (Chrome for Developers)

## Frontend Security

Protect users and data in the browser: understand the threats, prevent XSS and CSRF, and store credentials safely.

### Browser Security Model

core · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/frontend/web-security-basics

Same-origin policy, CORS, HTTPS, cookies and security headers: the rules that keep one site from attacking another.

The browser runs code from millions of untrusted sites side by side. Its security model is what stops a malicious page from reading your bank account in another tab. Frontend developers need to understand it because many vulnerabilities come from working around it carelessly.

#### The same-origin policy
An **origin** is scheme + host + port (`https://app.example.com:443`). Scripts can freely read responses and DOM only from their own origin. Two consequences:
- **CORS** is how a server opts in to let other origins read its responses (`Access-Control-Allow-Origin`). It is enforced by the browser, configured on the server, and it does not stop requests from being sent.
- Iframes and windows from other origins are isolated; communicate deliberately with `postMessage` and always check `event.origin`.

#### HTTPS everywhere
TLS protects data in transit and is required for many modern APIs (service workers, geolocation, clipboard). Add **HSTS** so browsers never downgrade to HTTP, and avoid mixed content.

#### Cookies
Know the attributes: `HttpOnly` (JavaScript cannot read it), `Secure` (HTTPS only), `SameSite=Lax|Strict|None` (controls cross-site sending), plus `Domain`, `Path` and expiry.

#### Security headers
`Content-Security-Policy`, `X-Content-Type-Options: nosniff`, `Referrer-Policy`, `Permissions-Policy` and `frame-ancestors` (clickjacking protection). Check them with your browser's DevTools or an observatory scanner.

#### A mindset
Anything in the browser is visible and modifiable by the user: never put secrets in frontend code, and never trust client-side checks for authorisation. The server is the security boundary.

#### Good enough to move on
You can explain the same-origin policy and CORS precisely, set secure cookie attributes, list the key security headers and explain why frontend validation is not security.

Key concepts: Origins and the same-origin policy, CORS preflight and headers, HTTPS, HSTS and mixed content, Cookie attributes: HttpOnly, Secure, SameSite, Security headers, postMessage and origin checks, No secrets in frontend code.

Mini project: Deploy a small app and harden it: secure session cookies, HSTS, nosniff, a strict referrer policy and frame-ancestors, then scan it with an online header checker and document the before and after results.

Self-check: A request to another origin fails with a CORS error. Did the request reach the server? Where must the fix go?

Resources:
- [Same-origin policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy) (MDN)
- [Web security](https://developer.mozilla.org/en-US/docs/Web/Security) (MDN)
- [OWASP Top Ten](https://owasp.org/www-project-top-ten/) (OWASP)

### Cross-Site Scripting (XSS) Prevention

core · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/frontend/xss

How attackers inject scripts through untrusted data, and how escaping, safe APIs and sanitisation stop them.

**XSS** happens when untrusted data ends up executing as code in your page. Once an attacker's script runs on your origin, it can do anything the user can: read data, make requests as them, steal tokens stored in JavaScript-accessible places and deface the page. It remains one of the most common web vulnerabilities.

#### Types
- **Stored XSS**: malicious input is saved (a comment, a profile name) and served to other users.
- **Reflected XSS**: input from the URL is echoed straight into the page.
- **DOM-based XSS**: client-side code moves data from a source (`location.hash`, `postMessage`, API data) into a dangerous sink.

#### Dangerous sinks
`innerHTML`, `outerHTML`, `document.write`, `insertAdjacentHTML`, `eval`, `new Function`, `setTimeout("string")`, `javascript:` URLs in `href` and inline event handler attributes.

#### Defences
- **Use safe APIs**: `textContent` instead of `innerHTML`. Frameworks escape text by default: React's JSX, Vue's `{{ }}` and Angular templates are safe for text.
- Framework escape hatches remove that protection: React's `dangerouslySetInnerHTML`, Vue's `v-html`, Svelte's `{@html}`. If you must render user HTML (Markdown, rich text), **sanitise** it with **DOMPurify** first.
- **Validate URLs** before using them in `href` or `src`: allow only `https:` (and maybe `mailto:`).
- Be careful with third-party scripts and dependencies; they run with full privileges.
- Add a **Content Security Policy** as defence in depth, and consider **Trusted Types** to lock down DOM sinks.

#### Good enough to move on
You can spot the XSS in a code snippet that uses innerHTML or an unchecked user-supplied link, fix it with safe APIs or DOMPurify, and explain why React escaping does not cover `href="javascript:..."`.

Key concepts: Stored, reflected and DOM-based XSS, Dangerous DOM sinks, Framework auto-escaping, dangerouslySetInnerHTML and v-html, Sanitising HTML with DOMPurify, Validating URLs and javascript: links, Trusted Types.

Mini project: Build a deliberately vulnerable comments page (innerHTML, unchecked profile links), exploit it locally with a harmless alert payload, then fix every hole and write a short explanation of each fix.

Self-check: React escapes text in JSX. Give an example of React code that is still vulnerable to XSS.

Resources:
- [Cross-site scripting (XSS)](https://developer.mozilla.org/en-US/docs/Web/Security/Attacks/XSS) (MDN)
- [OWASP XSS Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html) (OWASP)
- [DOMPurify](https://github.com/cure53/DOMPurify) (GitHub)

### Authentication, Token Storage and CSRF

core · advanced · about 4 h · https://www.internhack.in/roadmaps/tracks/frontend/auth-security

Where to keep sessions and tokens, why HttpOnly cookies are usually safest, and how CSRF attacks and defences work.

Almost every app has login, and the frontend decides where credentials live. The choice determines which attacks can steal them.

#### Storing credentials
- **HttpOnly, Secure, SameSite cookies** holding a session id or token: JavaScript cannot read them, so an XSS bug cannot exfiltrate them directly. This is the usual recommendation for browser apps.
- **localStorage or sessionStorage** with a JWT: simple, but any script on the page (including XSS or a compromised dependency) can read and steal it. Avoid for long-lived tokens.
- **In-memory tokens** with a refresh token in an HttpOnly cookie: a common SPA pattern that limits exposure.
- A **backend-for-frontend (BFF)** keeps third-party OAuth tokens on the server entirely.

#### CSRF
**Cross-Site Request Forgery** tricks a logged-in user's browser into sending a state-changing request to your site from another site, because cookies are attached automatically. Defences:
- `SameSite=Lax` (the modern default) or `Strict` cookies block most cross-site sends.
- **CSRF tokens** or checking the `Origin` header on the server for state-changing requests.
- Never change state with GET requests.

#### OAuth and third-party login
Use the **Authorization Code flow with PKCE** for SPAs and mobile, via a well-tested library or provider (Auth.js, Clerk, Auth0, Supabase, Firebase). Do not roll your own crypto or token parsing.

#### Frontend auth UX that stays secure
Hide UI the user cannot use, but always enforce permissions on the server. Handle expiry by refreshing once and then redirecting to login, clear client caches on logout and avoid putting tokens in URLs (they leak through history, logs and referrers).

#### Good enough to move on
You can argue for a storage choice with its trade-offs, explain a CSRF attack step by step and how SameSite and tokens stop it, and wire up an OAuth login with PKCE using a library.

Key concepts: Sessions vs JWTs, HttpOnly cookies vs localStorage, Refresh tokens and expiry handling, CSRF attacks and SameSite, CSRF tokens and Origin checks, OAuth 2.0 with PKCE, Auth providers and libraries, Backend-for-frontend pattern.

Mini project: Implement login for a React app using an HttpOnly session cookie from a small backend (or an auth provider), with protected routes, silent refresh, logout that clears the query cache and a CSRF defence you can explain.

Self-check: If your app has an XSS bug, why is a token in localStorage worse than one in an HttpOnly cookie, and what can the attacker still do in both cases?

Resources:
- [Cross-site request forgery (CSRF)](https://developer.mozilla.org/en-US/docs/Web/Security/Attacks/CSRF) (MDN)
- [OWASP Cheat Sheet Series](https://cheatsheetseries.owasp.org/) (OWASP)
- [Using HTTP cookies](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Cookies) (MDN)

### Content Security Policy and Supply-Chain Safety

recommended · advanced · about 3 h · https://www.internhack.in/roadmaps/tracks/frontend/csp

Limit what scripts can run with CSP, verify third-party code with SRI, and keep dependencies from becoming an attack vector.

Even careful teams ship bugs, so defence in depth matters. A **Content Security Policy** tells the browser which sources of scripts, styles, images and connections are allowed, so an injected script is blocked even if an XSS bug slips through.

#### CSP basics
Sent as the `Content-Security-Policy` header:
```
default-src 'self'; script-src 'self' 'nonce-r4nd0m'; img-src 'self' https://images.example.com; connect-src 'self' https://api.example.com; frame-ancestors 'none'; object-src 'none'; base-uri 'self'
```
- Prefer a **strict CSP** with per-request **nonces** or hashes plus `'strict-dynamic'` over long allowlists of domains.
- Avoid `'unsafe-inline'` and `'unsafe-eval'` for scripts; they defeat most of the protection.
- `frame-ancestors` prevents clickjacking by controlling who may embed your site.
- Roll out with `Content-Security-Policy-Report-Only` and a reporting endpoint, fix violations, then enforce.
- Frameworks such as Next.js document how to add nonces with middleware.

#### Subresource Integrity
When loading a script or stylesheet from a CDN, add an `integrity` hash and `crossorigin` attribute so the browser refuses a tampered file.

#### Dependency and supply-chain hygiene
- Your `node_modules` runs in your users' browsers. Keep dependencies few and reputable.
- Commit the lockfile, use `npm ci` in CI, and enable automated update and audit tools (Dependabot or Renovate, `npm audit`).
- Be wary of typo-squatted packages and install scripts; review new dependencies before adding them.
- Keep third-party tags (analytics, chat) under control and load them from trusted origins.

#### Good enough to move on
You can write a working CSP for an app you deployed, test it in report-only mode, add SRI to a CDN script and set up automated dependency updates.

Key concepts: CSP directives, Nonces, hashes and strict-dynamic, Report-only rollout, frame-ancestors and clickjacking, Subresource Integrity (SRI), Dependency auditing and updates, Lockfiles and npm ci.

Mini project: Add a nonce-based CSP to a Next.js or Vite app, deploy it in report-only mode, collect and fix violations, enforce it, and enable Dependabot or Renovate on the repository.

Self-check: Why does adding 'unsafe-inline' to script-src largely defeat the purpose of a CSP?

Resources:
- [Content Security Policy (CSP)](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CSP) (MDN)
- [Mitigate cross-site scripting with a strict CSP](https://web.dev/articles/strict-csp) (web.dev)
- [Subresource Integrity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity) (MDN)

## Rendering Strategies and Meta-Frameworks

Go beyond single-page apps with server rendering, static generation and full-stack frameworks (Next.js recommended).

### CSR, SSR, SSG, ISR and Streaming

core · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/frontend/rendering-strategies

Where and when HTML is produced, and how each strategy affects performance, SEO, cost and complexity.

A plain Vite React app does **client-side rendering (CSR)**: the server sends an almost empty HTML file and JavaScript builds the page in the browser. That is fine for dashboards behind a login, but it delays content, hurts SEO for public pages and depends entirely on the device's speed. Meta-frameworks let you choose, per route, where HTML is generated.

#### The strategies
- **CSR**: render in the browser. Simple hosting, rich interactivity, slower first content.
- **SSR (server-side rendering)**: render HTML on each request, then **hydrate** it in the browser to attach event handlers. Fresh, personalised and SEO friendly, but needs a server and adds per-request cost.
- **SSG (static site generation)**: render HTML at build time and serve it from a CDN. Fastest and cheapest, ideal for docs, blogs and marketing pages; content is only as fresh as the last build.
- **ISR / revalidation**: static pages that regenerate in the background after a time or on demand. Freshness without per-request rendering.
- **Streaming SSR**: send HTML in chunks as data resolves, using Suspense boundaries, so users see the shell immediately.
- **Islands and partial hydration**: ship static HTML and hydrate only interactive widgets (Astro's model). **Server Components** push the same idea further in React.
- **Edge rendering**: run SSR in data centres close to users.

#### Hydration pitfalls
Server and client must render the same markup. Using `Date.now()`, `Math.random()`, `window` or locale-dependent formatting during render causes hydration mismatch errors.

#### Choosing
Public, content-heavy pages favour SSG, ISR or SSR. Authenticated app screens can be CSR or SSR. Most real apps mix strategies per route.

#### Good enough to move on
Given a set of pages (landing, blog, product, dashboard), you can pick a strategy for each and justify it in terms of freshness, SEO, performance and cost.

Key concepts: Client-side rendering, Server-side rendering and hydration, Static site generation, Incremental static regeneration, Streaming SSR, Islands and partial hydration, Edge rendering, Hydration mismatches.

Mini project: Write a one-page architecture note for an e-commerce site choosing a rendering strategy for home, category, product, cart, account and blog pages, with reasons and expected trade-offs.

Self-check: Why does rendering the current time directly in a server-rendered component often cause a hydration warning?

Resources:
- [Rendering on the Web](https://web.dev/articles/rendering-on-the-web) (web.dev)
- [Server rendering APIs](https://react.dev/reference/react-dom/server) (react.dev)

### Next.js

recommended · intermediate · about 14 h · https://www.internhack.in/roadmaps/tracks/frontend/nextjs

The leading React framework: App Router, layouts, Server Components, data fetching and caching, Server Actions and middleware.

Next.js is the most widely used React framework and the one most job listings ask for. It adds file-based routing, server rendering, Server Components, data fetching, image and font optimisation and API endpoints on top of React.

#### App Router essentials
- **File-based routing** in `app/`: folders are URL segments; `page.tsx` renders a route; `layout.tsx` wraps children and persists across navigation; `loading.tsx` and `error.tsx` add Suspense and error boundaries automatically; `not-found.tsx` handles 404s.
- **Dynamic segments** (`[slug]`), route groups (`(marketing)`) and parallel or intercepting routes for advanced layouts.
- **Server Components by default**: fetch data in async components; add `"use client"` for interactive parts.
- **Server Actions** for mutations from forms, and **Route Handlers** (`route.ts`) for API endpoints and webhooks.
- **Middleware** (proxy) runs before requests for redirects, auth checks and rewrites.

#### Rendering and caching
Routes are static unless they use dynamic data (cookies, headers, uncached fetches). Understand how your Next.js version caches `fetch` results and rendered routes, and use revalidation (`revalidatePath`, `revalidateTag` or time-based) after mutations. Read the caching docs for your exact version; the defaults have changed across releases.

#### Built-ins
`next/image` (responsive, lazy images), `next/font` (self-hosted fonts with no layout shift), `next/link` (prefetching), the Metadata API for SEO and Open Graph.

#### Pitfalls
Marking whole trees `"use client"`, leaking secrets by importing server code into client components (use `server-only`), forgetting to authorise inside Server Actions and not knowing what is cached.

#### Good enough to move on
You can build and deploy a Next.js app with nested layouts, static and dynamic routes, server-side data fetching, a validated Server Action, loading and error states, and correct metadata.

Key concepts: App Router file conventions, Layouts, loading and error files, Dynamic routes and route groups, Data fetching in Server Components, Caching and revalidation, Server Actions and Route Handlers, Middleware, next/image, next/font and Metadata, Pages Router.

Mini project: Build a job board in Next.js: statically generated company pages with revalidation, a dynamic search page using search params, an authenticated dashboard with Server Actions to post jobs, and SEO metadata per job.

Self-check: You add a job with a Server Action but the list page still shows old data. What mechanism do you use to fix it?

Resources:
- [Next.js Documentation](https://nextjs.org/docs) (Vercel)
- [Learn Next.js](https://nextjs.org/learn) (Vercel)

### React Router Framework Mode (Remix)

alternative · intermediate · about 10 h · https://www.internhack.in/roadmaps/tracks/frontend/react-router-framework

Web-standards-first full-stack React with loaders, actions and nested routes; the evolution of Remix.

Remix merged into **React Router**, which now has a "framework mode" that provides server rendering, data loading and mutations around nested routes. Its philosophy is to lean on web standards: `Request`, `Response`, `FormData` and plain HTML forms.

#### Core ideas
- **Route modules**: each route file exports a component plus optional `loader` (read data on the server before rendering), `action` (handle form submissions and mutations), `meta`, `headers` and an `ErrorBoundary`.
- **Nested routes** load their data **in parallel**, avoiding request waterfalls.
- **Forms**: `<Form method="post">` submits to the route's action. After an action completes, loaders revalidate automatically, so the UI stays in sync without manual cache invalidation.
- **Progressive enhancement**: forms and links work before JavaScript loads, then get enhanced into SPA-style transitions.
- `useFetcher` for mutations that do not navigate (like buttons in a list), and `useNavigation` for pending UI.
- Rendering can be SSR, static prerendering or SPA mode, per app.
- Deploys to Node, serverless and edge runtimes through adapters.

#### When to choose it
Teams that value web fundamentals, simple mental models for data (loader in, action out), and portability across hosts. If you already know React Router in library mode, the step up is small.

#### Pitfalls
Doing client-side fetching in effects out of habit instead of using loaders; forgetting to validate and authorise inside actions; confusing library mode and framework mode documentation.

#### Good enough to move on
You can build a CRUD app with nested routes, loaders, actions with validation, optimistic UI via fetchers and per-route error boundaries.

Key concepts: Route modules, Loaders, Actions and Form, Automatic revalidation, useFetcher and pending UI, Progressive enhancement, Error boundaries per route.

Mini project: Build a contacts manager with nested list and detail routes, a create/edit form using actions and Zod validation, optimistic favourite toggles with useFetcher, and a per-route error boundary.

Self-check: After a successful action, why does the list update without you calling any cache invalidation function?

Resources:
- [React Router Framework Mode](https://reactrouter.com/start/framework/installation) (React Router)
- [React Router Documentation](https://reactrouter.com/home) (React Router)

### Nuxt

alternative · intermediate · about 10 h · https://www.internhack.in/roadmaps/tracks/frontend/nuxt

The full-stack framework for Vue: file-based routing, SSR and SSG, auto-imports, data fetching and server routes.

Nuxt is to Vue what Next.js is to React: a framework that adds routing, rendering strategies, data fetching and a server layer, with strong conventions and a smooth developer experience.

#### Core features
- **File-based routing** from the `pages/` directory, with dynamic routes (`[id].vue`), nested routes and **layouts**.
- **Auto-imports** for components, composables and Vue APIs, so files stay short.
- **Data fetching** with `useFetch` and `useAsyncData`, which run on the server during SSR and transfer the result to the client so it is not fetched twice.
- **Rendering modes**: universal SSR by default, plus static generation, SPA mode and **route rules** that mix strategies per path (for example prerender marketing pages, cache product pages, CSR the admin area).
- **Server routes** in `server/api` powered by Nitro, deployable to Node, serverless and edge platforms.
- **useState** for SSR-safe shared state, and Pinia for larger stores.
- **Modules** ecosystem for images, content, i18n, auth and more.
- SEO helpers such as `useHead` and `useSeoMeta`.

#### Pitfalls
Fetching with plain `$fetch` in components during SSR (it runs twice; use `useFetch`), accessing `window` on the server, and over-relying on auto-imports so that code becomes hard to trace.

#### Good enough to move on
You can build a Nuxt app with layouts, dynamic pages, `useFetch` data loading, a server API route and route rules that prerender some pages and server-render others.

Key concepts: File-based routing and layouts, Auto-imports, useFetch and useAsyncData, Rendering modes and route rules, Server routes with Nitro, Nuxt modules, SEO with useSeoMeta.

Mini project: Build a recipe site in Nuxt: prerendered home and category pages, server-rendered recipe pages loaded with useFetch from a server API route, and per-page SEO metadata.

Self-check: Why does useFetch avoid fetching the same data twice during SSR and hydration?

Resources:
- [Nuxt Documentation](https://nuxt.com/docs) (Nuxt)
- [Nitro](https://nitro.build/) (Nitro)

### Astro

alternative · intermediate · about 6 h · https://www.internhack.in/roadmaps/tracks/frontend/astro

A content-first framework that ships zero JavaScript by default and hydrates interactive islands built with any UI library.

Astro is built for content-driven websites: blogs, documentation, marketing sites and portfolios. It renders pages to HTML at build time (or on the server) and ships **no JavaScript by default**. Interactive parts become **islands** that hydrate independently.

#### Core ideas
- `.astro` components have a frontmatter script (runs at build or request time) and an HTML-like template. They never ship to the client.
- **Islands**: drop in React, Vue, Svelte or Solid components and choose when they hydrate with directives like `client:load`, `client:idle`, `client:visible` or `client:only`.
- **Content collections**: typed Markdown and MDX content with schemas, ideal for blogs and docs.
- **File-based routing** with static generation by default and on-demand SSR through adapters.
- **Server islands** and actions for dynamic pieces on otherwise static pages.
- View transitions for smooth page navigation without an SPA.

#### Why it matters
Because most of the page is static HTML, Astro sites are extremely fast and score well on Core Web Vitals with little effort. Using your existing React components as islands makes it easy to adopt.

#### When not to use it
Highly interactive apps such as dashboards, editors or chat, where nearly everything is dynamic, fit Next.js, React Router or SvelteKit better.

#### Good enough to move on
You can build a blog with content collections, a layout, a React island that hydrates only when visible, and deploy it statically with near-zero JavaScript.

Key concepts: Astro components and frontmatter, Islands and client directives, Content collections, File-based routing and static output, Using React or Vue components inside Astro, SSR adapters and server islands, View transitions.

Mini project: Build your developer portfolio and blog with Astro: content collections for posts, a React island for a project filter that hydrates on visible, RSS and sitemap, deployed as a static site.

Self-check: What is the difference between client:load and client:visible, and when would you choose each?

Resources:
- [Astro Documentation](https://docs.astro.build/) (Astro)
- [Islands architecture](https://docs.astro.build/en/concepts/islands/) (Astro)

### SvelteKit

alternative · intermediate · about 8 h · https://www.internhack.in/roadmaps/tracks/frontend/sveltekit

The official Svelte application framework with file-based routing, load functions, form actions and flexible rendering.

SvelteKit is the full-stack framework for Svelte. It combines Svelte's small, fast components with routing, server rendering, data loading and deployment adapters.

#### Core concepts
- **Routing** from `src/routes`: `+page.svelte` for a page, `+layout.svelte` for shared layouts, `[param]` folders for dynamic segments and `+error.svelte` for errors.
- **Load functions**: `+page.ts` (runs on server and client) or `+page.server.ts` (server only, safe for secrets and databases) return data that the page receives as a prop.
- **Form actions** in `+page.server.ts` handle `<form method="POST">` submissions, with `use:enhance` for progressive enhancement.
- **API routes** with `+server.ts` for JSON endpoints.
- **Hooks** (`hooks.server.ts`) for auth, logging and request handling.
- **Rendering options** per route: SSR, prerendering (`export const prerender = true`) or CSR only.
- **Adapters** deploy to Node, Vercel, Netlify, Cloudflare or static hosts.

#### Pitfalls
Putting secrets in universal `+page.ts` loads (they also run in the browser), forgetting validation in form actions, and mixing Svelte 4 and Svelte 5 syntax from older tutorials.

#### Good enough to move on
You can build a SvelteKit app with layouts, server load functions, form actions with validation and progressive enhancement, and deploy it with an adapter.

Key concepts: Routes, pages and layouts, Universal vs server load functions, Form actions and use:enhance, API routes with +server.ts, Hooks, Prerendering and rendering options, Deployment adapters.

Mini project: Build a link-sharing app in SvelteKit with server load functions reading from a database, form actions to add and upvote links with validation, a hooks-based session check and deployment with an adapter.

Self-check: Why should a database query live in +page.server.ts rather than +page.ts?

Resources:
- [SvelteKit Documentation](https://svelte.dev/docs/kit) (Svelte)
- [SvelteKit Tutorial](https://svelte.dev/tutorial/kit) (Svelte)

## Browser APIs and Progressive Web Apps

Use the platform directly: storage, background threads, offline support, notifications and real-time connections.

### Client-Side Storage

core · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/frontend/web-storage

localStorage, sessionStorage, IndexedDB, cookies and the Cache API: what each is for, limits and security implications.

Browsers offer several places to keep data on the user's device. Choosing the right one depends on size, structure, lifetime and who needs to read it.

#### The options
- **localStorage**: synchronous key-value strings that persist across sessions, per origin, roughly 5 MB. Good for small preferences like theme or a dismissed banner. Store objects with `JSON.stringify` and parse defensively.
- **sessionStorage**: same API, but scoped to one tab and cleared when it closes. Good for in-progress wizard state.
- **IndexedDB**: an asynchronous, transactional database for large structured data, blobs and offline-first apps. The raw API is verbose; use a wrapper such as `idb` or Dexie.
- **Cookies**: small, sent with every request to the server. Use them for sessions (HttpOnly), not general client storage.
- **Cache API**: stores request/response pairs, mainly used by service workers for offline assets.
- **Origin Private File System (OPFS)**: fast file storage for heavy apps (for example SQLite in the browser). Optional and advanced.

#### Practical concerns
- Storage can be **cleared** by the user or evicted under pressure; treat it as a cache unless you request persistence with `navigator.storage.persist()`.
- `navigator.storage.estimate()` reports quota.
- localStorage is synchronous: large reads block the main thread.
- Private browsing modes may limit or clear storage.
- Anything in storage is readable by any script on the origin, so never store secrets or long-lived tokens there.
- Sync between tabs with the `storage` event or `BroadcastChannel`.
- Version your stored data so an app update can migrate old formats.

#### Good enough to move on
You can persist user preferences in localStorage with safe parsing, cache a list of records in IndexedDB with a wrapper library and explain why a JWT should not live in localStorage.

Key concepts: localStorage and sessionStorage, IndexedDB with idb or Dexie, Cookies vs web storage, Cache API, Quotas, eviction and persistence, Cross-tab sync with BroadcastChannel, Origin Private File System, Security of stored data.

Mini project: Build a notes app that stores notes in IndexedDB (via Dexie), keeps UI preferences in localStorage, syncs changes across open tabs with BroadcastChannel and migrates an old storage format on startup.

Self-check: Why is localStorage a poor choice for 20 MB of offline data, and what should you use instead?

Resources:
- [Web Storage API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API) (MDN)
- [IndexedDB API](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API) (MDN)
- [Storage for the web](https://web.dev/articles/storage-for-the-web) (web.dev)

### Web Workers and Observer APIs

recommended · advanced · about 4 h · https://www.internhack.in/roadmaps/tracks/frontend/web-workers

Run heavy work off the main thread with Web Workers, and react efficiently to visibility, size and DOM changes with observers.

JavaScript on a page runs on one main thread shared with rendering and input handling. Two families of APIs help keep it responsive: **workers** move computation elsewhere, and **observers** replace expensive polling and scroll handlers.

#### Web Workers
A dedicated worker runs a script in a separate thread: `new Worker(new URL("./worker.ts", import.meta.url), { type: "module" })`. It has no DOM access; you exchange messages with `postMessage` and `onmessage`. Data is copied with structured cloning, or **transferred** (for `ArrayBuffer`s) to avoid copying.
- Good uses: parsing large files, image processing, search indexes, diffing, cryptography, heavy data transforms.
- **Comlink** wraps messaging so a worker feels like calling async functions.
- **Shared workers** serve several tabs; **service workers** are a different kind, covered in the PWA topic.

#### Observer APIs
- **IntersectionObserver**: notifies when an element enters or leaves the viewport. Use it for lazy loading, infinite scroll, analytics impressions and scroll-triggered animation, instead of listening to `scroll`.
- **ResizeObserver**: reacts to an element's size changes (charts, responsive components) rather than only the window's.
- **MutationObserver**: watches DOM changes, useful for integrating third-party widgets.
- **PerformanceObserver**: reads performance entries such as long tasks and layout shifts.

#### Other handy platform APIs
`requestAnimationFrame` for visual updates, `requestIdleCallback` for low-priority work, the Page Visibility API to pause work in hidden tabs, and Clipboard, Geolocation and Share APIs behind permissions.

#### Good enough to move on
You can move a CPU-heavy task into a worker and keep the UI smooth, and replace a scroll listener with IntersectionObserver for infinite scrolling.

Key concepts: Dedicated Web Workers, postMessage and transferable objects, Comlink, IntersectionObserver, ResizeObserver, MutationObserver, requestAnimationFrame and requestIdleCallback, Page Visibility API.

Mini project: Build a CSV explorer that parses a 50 MB file in a Web Worker with progress updates, renders rows with infinite scroll via IntersectionObserver and resizes its chart with ResizeObserver.

Self-check: Why can a Web Worker not update the DOM directly, and how does it send results back?

Resources:
- [Using Web Workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers) (MDN)
- [Intersection Observer API](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API) (MDN)
- [Resize Observer API](https://developer.mozilla.org/en-US/docs/Web/API/Resize_Observer_API) (MDN)

### Progressive Web Apps and Service Workers

recommended · advanced · about 6 h · https://www.internhack.in/roadmaps/tracks/frontend/pwa

Make web apps installable and offline-capable with a manifest and service worker caching, and re-engage users with push notifications.

A **Progressive Web App (PWA)** is a website that can be installed to the home screen or desktop, launch in its own window, work offline or on flaky networks and send notifications, all from one codebase.

#### The building blocks
- **HTTPS** (required).
- A **web app manifest** (`manifest.webmanifest`): name, icons, theme colour, `start_url` and `display: "standalone"`. This makes the app installable.
- A **service worker**: a script that runs in the background, separate from pages, and can intercept network requests from your origin.

#### Service worker lifecycle
Register it from your page; it goes through **install** (pre-cache core assets), **waiting** and **activate** (clean old caches). A new version waits until all tabs using the old one close, unless you prompt the user to update and call `skipWaiting`. Getting updates wrong is the most common PWA bug, so plan the update flow.

#### Caching strategies
- **Cache first** for hashed static assets.
- **Network first** for HTML and API data that should be fresh, falling back to cache offline.
- **Stale-while-revalidate** for things like avatars and non-critical data.
- An **offline fallback page** for navigation requests.
**Workbox**, or `vite-plugin-pwa` which uses it, generates most of this for you.

#### Notifications and more
The **Notifications API** shows system notifications after the user grants permission; the **Push API** lets a server wake the service worker to show one even when the site is closed (iOS supports this for installed web apps). Ask for permission in response to a user action with a clear reason, never on page load. **Background Sync** can retry failed requests when connectivity returns (limited browser support).

#### Good enough to move on
You can turn an app into an installable PWA with an offline fallback, sensible caching strategies, a working update prompt and an opt-in notification.

Key concepts: Web app manifest and installability, Service worker registration and lifecycle, Caching strategies, Offline fallback pages, Update flow and skipWaiting, Workbox and vite-plugin-pwa, Notifications and Push API, Background Sync.

Mini project: Turn your notes or expense app into a PWA with vite-plugin-pwa: installable, works offline with cached data, shows an 'update available' prompt and sends a reminder notification after the user opts in.

Self-check: You deployed a fix but users keep seeing the old version of your PWA. What part of the service worker lifecycle explains this?

Resources:
- [Learn PWA](https://web.dev/learn/pwa) (web.dev)
- [Service Worker API](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API) (MDN)
- [Workbox](https://developer.chrome.com/docs/workbox) (Chrome for Developers)

### Real-Time Communication: WebSockets and SSE

recommended · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/frontend/realtime

Push live updates to the browser with WebSockets or Server-Sent Events, handling reconnection, state and scaling concerns.

Chat, notifications, live dashboards, collaborative editing and multiplayer games need the server to push data without the client repeatedly asking. The browser offers several options.

#### The options
- **Polling**: fetch every few seconds. Simple and fine for low-frequency updates, wasteful for high frequency.
- **Server-Sent Events (SSE)**: `new EventSource("/events")` opens a long-lived HTTP response that streams text events from server to client. One direction only, automatic reconnection built in, works through most proxies. Ideal for notifications, feeds and streaming AI responses.
- **WebSockets**: `new WebSocket("wss://...")` gives a full-duplex, low-latency channel for messages in both directions. Ideal for chat, games and collaboration.
- **WebRTC**: peer-to-peer audio, video and data. Optional and specialised.
- **WebTransport**: a newer HTTP/3-based option; niche for now.

#### Doing it well
- **Reconnect** with exponential backoff and jitter; WebSockets do not reconnect on their own.
- On reconnect, **resync** missed data (send the last event id or refetch).
- Send **heartbeats** to detect dead connections.
- Define a message format (type plus payload), validate incoming messages and authenticate the connection (cookie or a short-lived token, never a long-lived secret in the URL).
- Integrate with your state: push updates into the TanStack Query cache or a store rather than keeping a separate copy.
- Close connections on unmount and when the tab is hidden if appropriate.
- Libraries and services such as Socket.IO, Ably, Pusher, Supabase Realtime and Liveblocks handle many of these concerns.

#### Good enough to move on
You can build a small chat with WebSockets that reconnects and resyncs, and a notification feed with SSE, and explain when to choose each.

Key concepts: Polling and long polling, Server-Sent Events, WebSocket API, Reconnection, backoff and resync, Authenticating real-time connections, Syncing pushed data with the query cache, Socket.IO and hosted realtime services, WebRTC.

Mini project: Build a live auction page: bids arrive over a WebSocket with reconnect and resync, an SSE stream shows outbid notifications, and incoming bids update the TanStack Query cache.

Self-check: When would you choose Server-Sent Events over WebSockets?

Resources:
- [The WebSocket API](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API) (MDN)
- [Using server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events) (MDN)
- [Socket.IO](https://socket.io/docs/v4/) (Socket.IO)

## Design Systems, Motion and Internationalisation

Build consistent, polished interfaces at team scale and make them work across languages and regions.

### Design Tokens and Theming

core · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/frontend/design-tokens

Encode colours, spacing, typography and radii as named tokens so design and code share one source of truth and themes are easy.

A **design system** is the shared language of a product: tokens, components, patterns and guidelines. Its foundation is **design tokens**, named values for every visual decision, used by designers in Figma and by developers in code.

#### Token layers
- **Primitive (base) tokens**: the raw palette and scales, such as `blue-600`, `space-4`, `radius-md`, `font-size-lg`.
- **Semantic tokens**: meaning, not appearance, such as `color-bg-surface`, `color-text-muted`, `color-border-danger`. Components use these.
- **Component tokens** (optional): `button-primary-bg` for fine control.

Themes (light, dark, high contrast, brand variants) simply remap semantic tokens to different primitives. Components never change.

#### In code
- Implement tokens as **CSS custom properties** on `:root` and theme selectors (`[data-theme="dark"]`), consumed by plain CSS, CSS Modules or a Tailwind theme.
- Respect `prefers-color-scheme` by default, let users override, persist the choice and set it before first paint to avoid a flash of the wrong theme.
- Tools like **Style Dictionary** or Figma variables exports can generate CSS, TypeScript and mobile formats from a single JSON source.
- Check every theme for **contrast** and visible focus rings.

#### Beyond tokens
Consistent spacing rhythm, a type scale, elevation (shadows) and motion durations are tokens too. Document when to use each, not just what exists.

#### Pitfalls
Using primitive tokens directly in components (dark mode then needs edits everywhere), inventing one-off values, and themes that were never tested for contrast.

#### Good enough to move on
You can define primitive and semantic tokens, build light and dark themes with no flash on load, and explain why components should reference semantic tokens.

Key concepts: What a design system includes, Primitive vs semantic tokens, Tokens as CSS custom properties, Light, dark and high-contrast themes, Avoiding theme flash on load, Style Dictionary and Figma variables, Type scale and spacing rhythm.

Mini project: Create a token set (primitives plus semantic tokens) for a fictional brand, implement light, dark and high-contrast themes with a persisted toggle and no flash on load, and verify contrast for each.

Self-check: Why should a Button use color-bg-accent rather than blue-600 directly?

Resources:
- [Using CSS custom properties](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_cascading_variables/Using_CSS_custom_properties) (MDN)
- [Style Dictionary](https://styledictionary.com/) (Style Dictionary)
- [Design Tokens Community Group](https://www.designtokens.org/) (W3C Community Group)

### Component Libraries: shadcn/ui and Radix

recommended · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/frontend/component-libraries

Build on accessible headless primitives (Radix, React Aria) and copy-in components (shadcn/ui) instead of reinventing dropdowns and dialogs.

Dialogs, dropdown menus, comboboxes, tooltips and date pickers are deceptively hard: focus management, keyboard support, ARIA, positioning and edge cases take weeks to get right. Mature teams build on libraries that already solve them.

#### Headless primitives
**Radix UI**, **React Aria** (Adobe), **Base UI** and **Ark UI** provide unstyled, accessible behaviour. You bring the styles. For example Radix's `Dialog.Root`, `Dialog.Trigger` and `Dialog.Content` handle focus trapping, Escape to close, scroll locking and ARIA for you.

#### shadcn/ui
Not a package you install as a dependency, but a collection of well-designed components built on Radix-style primitives and Tailwind that a CLI **copies into your codebase**. You own and edit the code, theme it with CSS variables and extend variants (often with `class-variance-authority`). It has become a very common starting point for React apps.

#### Full component suites
**MUI**, **Mantine**, **Chakra UI** and **Ant Design** provide complete styled component sets with theming. They are fast for internal tools and admin panels, at the cost of a stronger visual identity and bigger bundles.

#### Building your own components well
- Wrap primitives in your own components with a small, consistent API (`variant`, `size`, `asChild`).
- Forward refs and spread remaining props so components compose.
- Keep accessibility: labels, focus styles and keyboard behaviour must survive your styling.
- Document usage and do's and don'ts.

#### Good enough to move on
You can set up shadcn/ui in a project, customise its theme and a component's variants, and build a new accessible component from a Radix primitive.

Key concepts: Headless vs styled component libraries, Radix UI primitives, shadcn/ui, React Aria and Base UI, MUI, Mantine and Chakra, Variants with class-variance-authority, Component API design.

Mini project: Build a settings page from shadcn/ui components themed with your own tokens, then create a new accessible Combobox or Command menu component from primitives with keyboard navigation.

Self-check: What does a headless library like Radix give you, and what is still your responsibility?

Resources:
- [shadcn/ui](https://ui.shadcn.com/docs) (shadcn/ui)
- [Radix Primitives](https://www.radix-ui.com/primitives/docs/overview/introduction) (Radix)
- [React Aria](https://react-spectrum.adobe.com/react-aria/) (Adobe)

### Storybook and Component Documentation

optional · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/frontend/storybook

Develop, document and test components in isolation with Storybook stories, controls, docs and visual and interaction tests.

**Storybook** is a workshop for UI components. You write **stories**, each showing a component in one state (default, loading, error, long text, right-to-left), and Storybook renders them in an isolated app with controls to tweak props live.

#### Why teams use it
- **Build in isolation**: work on a component's hard states without clicking through the app to reach them.
- **Living documentation**: autodocs pages list props, variants and usage examples for designers and other developers.
- **Review**: product and design can see changes in a deployed Storybook before merging.
- **Testing**: stories double as test cases.

#### Writing stories
Component Story Format: a default export describes the component, and named exports are stories with `args`. Use **decorators** to wrap stories in providers (theme, router, query client), and MSW handlers to mock data. Cover edge cases, not just the happy path.

#### Testing with stories
- **Interaction tests** with `play` functions click and type inside a story and assert results, powered by Testing Library and Vitest.
- **Accessibility checks** with the a11y addon run axe on every story.
- **Visual regression testing** with Chromatic or Playwright screenshots catches unintended style changes.

#### Alternatives
Ladle and Histoire are lighter options; many small teams simply document components in MDX or a docs site. Storybook matters most when a component library is shared across teams or apps.

#### Good enough to move on
You can add Storybook to a project, write stories covering the states of five components, add an interaction test and an accessibility check, and publish it for review.

Key concepts: Stories and args, Controls and autodocs, Decorators and mocked data, Interaction tests with play functions, Accessibility addon, Visual regression testing, Publishing Storybook for review.

Mini project: Add Storybook to your component library, write stories for every state of Button, Input, Dialog, Toast and DataTable, add a play-function test for the Dialog and run the a11y addon on all stories.

Self-check: How does writing a story for a component's error state save time compared with testing it inside the full app?

Resources:
- [Storybook documentation](https://storybook.js.org/docs) (Storybook)
- [Writing stories](https://storybook.js.org/docs/writing-stories) (Storybook)

### UI Animation with Motion Libraries

optional · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/frontend/motion

Add purposeful motion with Motion (Framer Motion), the View Transitions API and, when needed, GSAP, while respecting reduced motion.

Good motion explains what changed: a panel slides from the button that opened it, a list item fades out when deleted, a page transition shows where you came from. Bad motion is slow, distracting or nauseating. Master CSS transitions first; reach for libraries when you need orchestration, gestures or layout animation.

#### Motion (formerly Framer Motion)
The most popular React animation library:
- `<motion.div animate={{ opacity: 1, y: 0 }} initial={{ opacity: 0, y: 8 }} />` declarative animations.
- `AnimatePresence` animates components as they **unmount**, which CSS alone cannot do.
- **Layout animations** (`layout` prop, `layoutId`) smoothly animate size and position changes, including shared element transitions.
- Gestures (hover, tap, drag), variants for orchestrating children, and spring physics for natural feel.

#### View Transitions API
A browser API that animates between two DOM states or pages: `document.startViewTransition(() => updateDom())`, styled with CSS pseudo-elements. Cross-document view transitions work for multi-page sites too. Frameworks increasingly integrate it.

#### GSAP (optional)
A powerful timeline-based animation library for complex, choreographed sequences, scroll-driven storytelling (ScrollTrigger) and SVG animation. Common on marketing and award-style sites. CSS **scroll-driven animations** now cover some of these cases natively.

#### Principles
- Keep UI transitions short (roughly 150 to 300 ms) with easing that decelerates.
- Animate `transform` and `opacity` for smoothness.
- Always honour `prefers-reduced-motion` (Motion's `useReducedMotion`), replacing movement with fades or nothing.
- Motion should never block the user from acting.

#### Good enough to move on
You can animate a list with enter and exit transitions, a shared-element card-to-detail transition and a reduced-motion alternative for each.

Key concepts: Purposeful motion principles, Motion (Framer Motion) basics, AnimatePresence exit animations, Layout and shared element animations, View Transitions API, GSAP and ScrollTrigger, Reduced motion support.

Mini project: Build a photo gallery where thumbnails expand into a detail view with a shared-element transition, deleted photos animate out with AnimatePresence, and everything degrades to simple fades under prefers-reduced-motion.

Self-check: Why can CSS transitions alone not animate a component that React removes from the DOM, and how does AnimatePresence solve it?

Resources:
- [Motion for React](https://motion.dev/docs/react) (Motion)
- [View Transition API](https://developer.mozilla.org/en-US/docs/Web/API/View_Transition_API) (MDN)
- [GSAP documentation](https://gsap.com/docs/v3/) (GSAP)

### Internationalisation and Localisation

optional · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/frontend/i18n

Prepare apps for many languages and regions: message catalogues, plurals, Intl formatting, right-to-left layouts and locale routing.

**Internationalisation (i18n)** is engineering the app so it can be adapted; **localisation (l10n)** is the adaptation itself: translated text, local formats and cultural conventions. Retrofitting i18n into a large app is painful, so learn the patterns early.

#### Messages and translations
- Never hard-code user-facing strings. Use keys in **message catalogues** (JSON per locale) through a library: **react-i18next**, **FormatJS / react-intl**, **next-intl** for Next.js, or **Lingui**.
- Use the **ICU message format** for variables, **plurals** and select: `{count, plural, one {# item} other {# items}}`. Languages have different plural rules (Arabic has six forms), so never build sentences by concatenation.
- Give translators context (descriptions, screenshots) and never split sentences across keys.

#### Formatting with Intl
The built-in `Intl` APIs format per locale without extra libraries: `Intl.NumberFormat` (numbers, currencies, units), `Intl.DateTimeFormat` and `Intl.RelativeTimeFormat` ("3 days ago"), `Intl.PluralRules`, `Intl.ListFormat` and `Intl.Collator` for sorting. Store dates in UTC and format in the user's time zone.

#### Layout and direction
- Right-to-left languages (Arabic, Hebrew, Urdu): set `dir="rtl"` and use **logical CSS properties** (`margin-inline-start`, `padding-block`, `inset-inline-end`) instead of left and right.
- Allow text to expand (German can be 30% longer); avoid fixed-width buttons.
- Set the `lang` attribute so screen readers pronounce text correctly.

#### Locale routing and SEO
Use locale prefixes or domains (`/en/`, `/fr/`), detect but do not force the user's language, and add `hreflang` alternates.

#### Good enough to move on
You can externalise all strings in an app, add a second language with plurals, format dates and currency with Intl and make the layout work in RTL.

Key concepts: i18n vs l10n, Message catalogues and keys, ICU plurals and select, Intl number, date and relative time formatting, Right-to-left and logical CSS properties, react-i18next, FormatJS and next-intl, Locale routing and hreflang, Translation workflows.

Mini project: Localise your catalogue app into English, Hindi and Arabic: externalised strings with plurals, Intl-formatted prices and dates, a language switcher with locale routes and a correct RTL layout for Arabic.

Self-check: Why is `count + " items"` wrong for internationalised apps, even after translating the word items?

Resources:
- [Intl](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl) (MDN)
- [react-i18next](https://react.i18next.com/) (i18next)
- [FormatJS](https://formatjs.github.io/) (FormatJS)

## Shipping to Production and Beyond

Deploy with confidence, automate quality checks, monitor real users, optionally take your skills to mobile and desktop, and prove it all with a capstone.

### Deploying Frontend Apps

core · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/frontend/deployment

Host static and server-rendered apps on Vercel, Netlify or Cloudflare with preview deployments, custom domains, rollbacks and monitoring.

A project nobody can open is not a portfolio piece. Modern frontend hosting makes deployment almost effortless, but you still need to understand what is being deployed and how it behaves in production.

#### What you deploy
- **Static builds** (a Vite SPA, an Astro or SSG site): a folder of HTML, JS, CSS and assets served from a CDN. Configure an **SPA fallback** so deep links serve `index.html`.
- **Server-rendered apps** (Next.js, Nuxt, SvelteKit, React Router): code that also runs on servers, serverless functions or edge runtimes.

#### Platforms
- **Vercel**: first-class Next.js support, previews per pull request and edge functions.
- **Netlify**: great for static and Jamstack sites, forms, functions and redirects files.
- **Cloudflare Pages / Workers**: a global edge network, generous free tier, edge-first runtime.
- **GitHub Pages** for purely static projects; containers on any cloud when you need full control.

#### Everyday features
- Connect the Git repository: every push to `main` deploys production, every pull request gets a **preview URL** for review.
- **Custom domains** with automatic HTTPS, redirects, rewrites and custom headers (security and caching).
- **Instant rollbacks** to a previous deployment.
- **Monitoring**: error tracking (Sentry or similar) with uploaded source maps so stack traces are readable, plus analytics and Core Web Vitals from real users.

#### Pitfalls
Refreshing a deep link returns 404 (missing SPA fallback); build succeeds locally but fails in CI (different Node version, case-sensitive imports); unreadable production errors (no source maps); and surprise bills from unbounded serverless usage.

#### Good enough to move on
You have deployed at least one SPA and one server-rendered app with custom domains, previews on pull requests, security and caching headers, and error tracking with source maps.

Key concepts: Static vs server-rendered deployments, Vercel, Netlify, Cloudflare Pages and Workers, Preview deployments, Custom domains, redirects and headers, SPA fallback routing, Rollbacks, Error tracking with source maps.

Mini project: Deploy your React app to Vercel or Netlify and a static site to Cloudflare Pages, each with a custom domain, preview deployments on pull requests, caching and security headers, and Sentry error tracking with source maps.

Self-check: Your SPA works when you navigate from the home page but /settings returns 404 on refresh. Why, and how do you fix it on the host?

Resources:
- [Vercel Documentation](https://vercel.com/docs) (Vercel)
- [Netlify Docs](https://docs.netlify.com/) (Netlify)
- [Cloudflare Pages](https://developers.cloudflare.com/pages/) (Cloudflare)
- [Deploying a Static Site](https://vite.dev/guide/static-deploy) (Vite)

### Environment Variables and Configuration

core · intermediate · about 2 h · https://www.internhack.in/roadmaps/tracks/frontend/env-config

Manage per-environment configuration safely, understanding the difference between build-time public variables and server-only secrets.

Apps behave differently in development, preview and production: different API URLs, analytics keys and feature flags. Environment variables carry this configuration, and frontend developers must understand one crucial rule: **anything bundled into client JavaScript is public**.

#### Public vs server-only
- Build tools only expose variables with a prefix to client code: `VITE_` in Vite (`import.meta.env.VITE_API_URL`), `NEXT_PUBLIC_` in Next.js, `PUBLIC_` in Astro and SvelteKit. These are **inlined at build time** and visible to anyone who opens DevTools.
- Unprefixed variables stay on the server (Next.js server components, route handlers, SvelteKit server loads). This is where API secrets, database URLs and private keys belong.
- If the browser needs data that requires a secret, call your own server or a serverless function that holds the secret.

#### Files and environments
- `.env` for defaults, `.env.local` for personal overrides (git-ignored), and mode-specific files like `.env.production`.
- Commit a `.env.example` documenting required variables without real values.
- Set real values in your hosting dashboard per environment (production, preview, development) and in CI secrets.
- Because public variables are baked in at build time, changing them requires a **rebuild**.

#### Safety and validation
- Validate variables at startup with a schema (Zod) so a missing value fails the build, not a user session.
- Type them (`vite-env.d.ts`) for autocomplete.
- If a secret ever lands in a client bundle or Git history, treat it as leaked: **rotate it**.

#### Feature flags
Runtime flags (LaunchDarkly, GrowthBook, PostHog, or a simple config endpoint) let you ship code dark and enable it gradually without redeploying.

#### Good enough to move on
You can configure an app for three environments, keep secrets server-side, validate and type variables, and explain why a `VITE_` variable is not secret.

Key concepts: Build-time public variables, Server-only secrets, VITE_ and NEXT_PUBLIC_ prefixes, .env files and .env.example, Per-environment values on the host, Validating env vars with a schema, Rotating leaked secrets, Feature flags.

Mini project: Configure your deployed app with separate API URLs for development, preview and production, move a third-party API key behind a serverless function, and fail the build when a required variable is missing.

Self-check: A teammate puts a payment provider's secret key in VITE_PAYMENT_SECRET. What is the problem and what should they do instead?

Resources:
- [Env Variables and Modes](https://vite.dev/guide/env-and-mode) (Vite)
- [Environment Variables in Next.js](https://nextjs.org/docs/app/guides/environment-variables) (Vercel)

### Continuous Integration for Frontend Projects

core · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/frontend/frontend-ci

Automate type checks, linting, tests, builds and previews on every pull request with GitHub Actions.

**Continuous integration (CI)** runs your quality checks automatically on every push and pull request, so broken code is caught before it merges. For a frontend team it is also where performance, accessibility and bundle-size budgets are enforced.

#### A typical pipeline
1. **Install** with the lockfile (`npm ci` or `pnpm install --frozen-lockfile`), with dependency caching for speed.
2. **Type check** (`tsc --noEmit`) and **lint** (ESLint) and check formatting (Prettier).
3. **Unit and component tests** (Vitest) with coverage.
4. **Build** the production bundle.
5. **End-to-end tests** (Playwright) against the build or a preview deployment, uploading traces on failure.
6. Optional gates: **bundle size** limits, Lighthouse CI budgets, axe accessibility checks, visual regression.

#### GitHub Actions basics
Workflows are YAML files in `.github/workflows/`: triggers (`on: pull_request`), jobs that run on hosted runners, steps using actions like `actions/checkout` and `actions/setup-node` (pin the Node version), and secrets for tokens. Run independent jobs in parallel and use a matrix for multiple browsers or Node versions.

#### Team practices
- **Branch protection**: require CI to pass and a review before merging to `main`.
- Keep CI **fast** (under about 10 minutes) through caching, parallelism and running only affected checks in monorepos.
- Treat flaky tests as bugs; quarantine and fix them rather than re-running until green.
- Use **pre-commit hooks** (Husky plus lint-staged) for instant local feedback, but never rely on them alone.
- **Continuous deployment**: hosting platforms deploy `main` automatically once CI passes.

#### Good enough to move on
Your project has a GitHub Actions workflow that type checks, lints, tests, builds and runs E2E tests on every pull request, with branch protection requiring it to pass.

Key concepts: What CI is and why it matters, GitHub Actions workflows, jobs and steps, Caching dependencies, Typecheck, lint, test and build stages, E2E tests in CI, Branch protection and required checks, Bundle size and Lighthouse budgets, Husky and lint-staged.

Mini project: Write a GitHub Actions workflow for your capstone repository with parallel lint/typecheck/test jobs, a build, Playwright E2E against the preview URL, a bundle-size check and branch protection on main.

Self-check: Why should CI install dependencies with npm ci rather than npm install?

Resources:
- [GitHub Actions documentation](https://docs.github.com/en/actions) (GitHub)
- [Building and testing Node.js](https://docs.github.com/en/actions/use-cases-and-examples/building-and-testing/building-and-testing-nodejs) (GitHub)
- [Playwright Continuous Integration](https://playwright.dev/docs/ci) (Playwright)

### Mobile Apps with React Native

optional · intermediate · about 10 h · https://www.internhack.in/roadmaps/tracks/frontend/react-native

Reuse your React and TypeScript skills to build native iOS and Android apps with React Native and Expo.

React Native lets you build real native mobile apps with React. Instead of rendering to the DOM, components like `<View>`, `<Text>`, `<Pressable>` and `<FlatList>` render to native platform views. Your knowledge of components, hooks, state management, TanStack Query and TypeScript transfers almost directly.

#### Start with Expo
**Expo** is the recommended way to build React Native apps. It provides a managed toolchain, a large set of native modules (camera, notifications, location, secure storage), **Expo Router** for file-based navigation, development builds and cloud builds and store submission with EAS. You can preview on a real phone within minutes.

#### What is different from the web
- **Styling** uses a JavaScript subset of CSS with flexbox as the default layout (`flexDirection: "column"` by default). There is no cascade; styles are per component. NativeWind brings Tailwind-style classes.
- **Navigation** is stack, tab and drawer based rather than URL-first.
- **Lists** must be virtualised (`FlatList`, FlashList) for performance.
- **Platform differences** between iOS and Android, safe areas, keyboards and permissions.
- **Storage**: AsyncStorage or MMKV for data, SecureStore for tokens.
- **Release**: app store review, versioning, and over-the-air updates for JavaScript changes.

#### When it makes sense
A frontend developer who can ship to web and mobile is valuable in startups. For deeper mobile work, follow the dedicated mobile track.

#### Good enough to move on
You can build and run an Expo app with a couple of screens, tab navigation, a list loaded from an API and a native feature such as notifications or the camera.

Key concepts: Core components: View, Text, Pressable, Expo and Expo Router, Styling and flexbox in React Native, Virtualised lists, Native modules and permissions, Secure storage, Builds, store release and OTA updates.

Mini project: Build a mobile companion app for your capstone with Expo: tab navigation, a list screen fetching the same API with TanStack Query, a detail screen and local push notification reminders.

Self-check: Which of your React web skills transfer directly to React Native, and which web concepts (like CSS cascade or the DOM) do not?

Resources:
- [React Native](https://reactnative.dev/docs/getting-started) (Meta)
- [Expo Documentation](https://docs.expo.dev/) (Expo)

### Desktop Apps with Electron and Tauri

optional · advanced · about 6 h · https://www.internhack.in/roadmaps/tracks/frontend/desktop-apps

Package web apps as desktop applications with Electron or the lighter Tauri, and understand their security models.

Many well-known desktop apps (code editors, chat, design and note-taking tools) are web apps running inside a desktop shell. If you can build a web frontend, you can ship a desktop app.

#### Electron
Bundles Chromium and Node.js with your app. You write a **main process** (Node: windows, menus, file system, native dialogs) and **renderer processes** (your web UI), connected through IPC. Huge ecosystem and consistent rendering across platforms; the cost is large download size and memory use.

#### Tauri
Uses the operating system's own webview (WebView2, WKWebView, WebKitGTK) with a **Rust** backend, producing much smaller binaries and lower memory use. You call backend commands from the frontend through a typed API, and Tauri 2 also targets iOS and Android. Rendering differences between system webviews need testing.

#### Security is critical
Desktop apps have access to the user's machine, so an XSS bug can become remote code execution.
- In Electron: keep `contextIsolation` on and `nodeIntegration` off, expose only narrow APIs through a **preload script** with `contextBridge`, validate IPC messages and never load remote untrusted content with privileges.
- In Tauri: use the **capabilities and permissions** system to allow only the commands and paths you need.
- Apply a Content Security Policy in both.

#### Shipping
Code signing and notarisation (macOS), installers per platform, and **auto-updates**.

#### Good enough to move on
You can wrap an existing web app in Electron or Tauri, add one native feature (file open/save or a tray menu) through a safe bridge, and produce an installer for your platform.

Key concepts: Electron main and renderer processes, IPC and preload scripts, Tauri and system webviews, Desktop security hardening, Native features: files, menus, tray, Packaging, signing and auto-updates.

Mini project: Turn your Markdown notes web app into a desktop app with Tauri or Electron that opens and saves files from disk through a safe, validated bridge and ships as an installer.

Self-check: Why is enabling nodeIntegration in an Electron renderer that displays user content so dangerous?

Resources:
- [Electron Documentation](https://www.electronjs.org/docs/latest/) (Electron)
- [Electron Security](https://www.electronjs.org/docs/latest/tutorial/security) (Electron)
- [Tauri](https://v2.tauri.app/start/) (Tauri)

### Capstone: A Production-Grade Frontend Application

core · advanced · about 40 h · https://www.internhack.in/roadmaps/tracks/frontend/capstone

Design, build, test, secure, optimise and deploy one substantial application that demonstrates everything in this track.

The capstone turns knowledge into evidence. Recruiters and interviewers care far more about one polished, deployed, well-explained project than ten tutorial clones. Aim for something that solves a real problem for real users, ideally including you.

#### Pick a project with real depth
Good options: a job application tracker, a collaborative kanban board, a budgeting app with charts, a marketplace with search and checkout, a course platform with progress tracking. It should have authentication, several related data types, create/update/delete flows, search or filtering and at least one real-time or offline feature.

#### Required checklist
- **Stack**: TypeScript, React with Next.js (or your chosen framework), a styling approach from this track, TanStack Query or framework loaders, React Hook Form plus Zod.
- **Architecture**: clear folder structure, a typed API layer, state placed deliberately, URL-driven filters.
- **Quality**: unit tests for logic, component tests for key flows, 3 or more Playwright E2E tests, CI on every pull request.
- **Accessibility**: keyboard operable, axe clean, tested with a screen reader, WCAG AA contrast.
- **Performance**: good Core Web Vitals on a throttled mobile profile, optimised images, code-split routes.
- **Security**: safe auth storage, XSS-safe rendering, a CSP, no secrets in the client.
- **Production**: deployed with a custom domain, previews, environment config and error tracking.

#### Present it well
Write a README with a live link, screenshots or a short demo video, the architecture and key decisions (and trade-offs you rejected), how to run and test it, and what you would do next. Keep a clean commit history with meaningful pull requests.

#### Good enough to move on
A stranger can open your live app, use it on a phone with a keyboard or screen reader, read your README and understand why you built it the way you did.

Key concepts: Choosing a meaningful project, Architecture and data modelling, Authentication and authorisation, Testing strategy and CI, Accessibility and performance audits, Security review, Production deployment and monitoring, README, demo and case study, Real-time or offline feature.

Mini project: Build and deploy a job application tracker (or similar) that meets every item on the checklist, then write a case study covering architecture, trade-offs, test strategy and measured Core Web Vitals.

Self-check: Can you walk an interviewer through one hard technical decision in your capstone, the alternatives you considered and how you would change it at 10 times the users?

Resources:
- [Next.js Documentation](https://nextjs.org/docs) (Vercel)
- [web.dev Learn](https://web.dev/learn) (web.dev)
- [About READMEs](https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-readmes) (GitHub)

## Related

- [Career roadmaps](https://www.internhack.in/roadmaps)
