{"canonical_url":"https://engineer.company/glossary/single-page-application/","content_markdown":"# Single-page application\n\n## What it is\n\nA single-page application, also written single-page app and usually shortened\nto SPA, is a web application that loads one HTML document and then changes that\ndocument with JavaScript instead of asking the server for a new page. Clicking a\nlink inside it does not unload the page. A script catches the click, fetches\nwhatever data the next view needs, rewrites part of the DOM and updates the\naddress bar, so the URL still says where the reader is.\n\nNo standard owns the term, and the people who build the tools admit as much.\nNext.js opens its guide to the subject with “The definition of a SPA varies.”\nand then fixes one for its own use, which it calls a strict SPA. It has two\ntraits. A single HTML file serves the whole app, and JavaScript in the browser\ntakes care of every route, every page transition and every request for data. And\nthe page never reloads in full: when the route changes, scripts on the client\nrewrite the DOM of the page that is already open and load data when it is\nwanted, instead of asking the server for a fresh document. This article uses\nthat definition because it is the most direct one on offer and names the\nproperty everything else depends on, a document that is never replaced.\n\nThe browser parts are standard. The HTML Standard's History interface gives a\npage `history.pushState()`, which adds a new entry to the session history and\nsets the URL without loading anything, and `history.replaceState()`, which\nrewrites the current entry instead. When the reader goes Back or Forward between\nthose entries, the browser fires a `popstate` event at the window and leaves the\nredrawing to the page. The newer Navigation API, which the standard presents as\nthe successor to the classic location and history APIs, works from the other\nend: a `navigate` event fires when a navigation begins, and its `intercept()`\nmethod turns that navigation into a same-document one that the page handles\nitself.\n\nThe opposite is the ordinary multi-page website, where every link asks the\nserver for a fresh document and the browser throws the old one away. Whether a\npage's HTML is made once by a static site generator or on each request by\nserver-side rendering is a separate question, about how the HTML is produced\nrather than what happens after it arrives. Next.js blurs the line on purpose:\nits static export writes an HTML file for every route, and moving between them\nstill happens on the client.\n\n## Why it matters\n\nBecause the document is never replaced, whatever lives in it survives a click:\na half-filled form, a playing video, the scroll position of a side panel, data\nalready fetched. Only the data the next view needs has to cross the network,\nnot a whole new page with its header, styles and scripts. A change of view can\nbe as small as rewriting one region of the page.\n\nNext.js names the costs in the same breath as the definition. A strict SPA often\nhas to load a large amount of JavaScript before the page can be interactive, and\nclient data waterfalls, where one request can start only after another has come\nback, are hard to manage. Anything that reads the page without running scripts\npays as well. With one HTML file behind every route, a crawler that does not run\nJavaScript gets the same nearly empty document whatever URL it asks for. Next.js\nmakes the same point about its own browser-only components: anything that\nindexes the page without running scripts gets the fallback, not the component.\n\nIts answer is to keep the client-side navigation and move the rest. Next.js\nsplits JavaScript bundles automatically and generates multiple HTML entry points\ninto different routes, so a visitor does not load code a route does not need.\nIts `next/link` component prefetches routes, which makes route changes feel as\nimmediate as those in a fully client-rendered SPA while keeping the\napplication's routing state in the URL, where it can be linked to and shared. A\nstatic export goes further and writes a fully rendered page for each route, so\nvisitors get content without waiting for the client bundle, while client-side\ntransitions between pages stay as quick as in a strict SPA.\n\nNor is the choice made once and for all. Next.js describes a project that starts\nas a static site, or even as a strict SPA rendered entirely on the client, and\nadds server features as it grows, and it says an existing SPA can move across\nwithout being rewritten from scratch.\n\n## What it looks like in practice\n\nThe router below, written for this article, is the smallest working version of\nthe idea. It assumes the page has a `\u003cmain\u003e` element and that the server\nanswers every app path with the same HTML document. The two views stand in for\nwhatever the app really shows.\n\n```js\n// router.js\nconst views = {\n  \"/\": { title: \"Orders\", text: \"Your recent orders.\" },\n  \"/settings\": { title: \"Settings\", text: \"Delivery preferences.\" },\n};\nconst main = document.querySelector(\"main\");\n\nfunction show(path, moveFocus) {\n  const view = views[path] ?? views[\"/\"];\n  const heading = document.createElement(\"h1\");\n  const body = document.createElement(\"p\");\n  heading.textContent = view.title;\n  heading.tabIndex = -1;\n  body.textContent = view.text;\n  main.replaceChildren(heading, body);\n  document.title = view.title;\n  if (moveFocus) heading.focus();\n}\n\ndocument.addEventListener(\"click\", (event) =\u003e {\n  const link = event.target.closest(\"a[href]\");\n  const modified = event.metaKey || event.ctrlKey || event.shiftKey;\n  if (!link || link.origin !== location.origin) return;\n  if (modified || event.button !== 0) return;\n  event.preventDefault();\n  history.pushState(null, \"\", link.href);\n  show(location.pathname, true);\n});\n\nwindow.addEventListener(\"popstate\", () =\u003e show(location.pathname, true));\nshow(location.pathname, false);\n```\n\nThe click handler takes over plain left clicks on links to the same origin and\nlets modified clicks through, so opening a link in a new tab still works.\n`preventDefault()` stops the browser's own navigation, and `pushState()` records\na new session history entry with the link's URL; its middle argument is there\nonly for historical reasons, which is why it is an empty string. `show()`\nreplaces the view, sets the document title and moves focus to the new heading,\nwhich a `tabIndex` of `-1` makes focusable from script while keeping it out of\nthe Tab order. The `popstate` listener redraws the matching view when the\nreader goes Back or Forward, and the last line draws whichever URL the page was\nopened at, which only works if the server sends the same document for\n`/settings` as for `/`. A real app would also show its own not-found view\ninstead of quietly falling back to the start page, and would leave links to\nfiles and to other parts of the site alone.\n\nIn the founder's current work under NextMariner, the Next.js 16 frontend shows\nthe cost side of this on a real product.\n[Its portfolio entry](/portfolio/built-the-next-js-16-frontend-ssr-ssg-and-csr/)\ndescribes an authenticated dashboard that had to feel quick and stay genuinely\ninteractive, and names what happens when everything is fetched on the client:\nthe first load drags, and the N+1 pattern appears, with every component waking\nup and sending its own request until a single page becomes a cascade of round\ntrips. That is the client data waterfall the Next.js guide warns about, met in\npractice. The fix kept client-side interactivity where it mattered and moved\nthe first fetch to the server. On the dashboard and the big directory listings,\na factory called `createPrefetchedServerPage` hands each page to the client\nwith its data already in place. The entry is candid about the rest: the other\nauthenticated pages are still rendered on the client and wait their turn, so\nit describes a migration that works and has an obvious next page, not one that\nis complete.\n\n## Where it goes wrong\n\n**The Back button leaves the app.** If a script swaps views without calling\n`pushState()`, the session history has no entry for them. Back skips every view\nthe reader saw and leaves the app altogether, and a reload lands on whatever\nURL the app was first opened at. Push an entry for each view a reader would\ncall a page, use `replaceState()` for changes that should not become steps of\ntheir own, such as a filter being typed, and handle `popstate`. Next.js argues\nfor keeping routing state in the URL for the same reason: it is what lets a\nview be linked to and shared.\n\n**A deep link meets a server that knows one file.** In a strict SPA one HTML\nfile serves every route, but the address bar shows `/settings`, and that is\nwhat the browser asks for on a reload or when someone opens a shared link. A\nserver that only has `index.html` answers with a 404. Either configure the\nserver to answer every app path with the document, or generate a file per\nroute. Next.js's static export does the second: its `out` folder holds files\nsuch as `index.html`, `404.html` and `blog/post-1.html`, and its guide shows an\nnginx rule, `try_files $uri $uri.html $uri/ =404;`, that maps a clean URL onto\nthe matching file.\n\n**Focus stays where the old view was.** `pushState()` changes the session\nhistory and the URL and nothing else. After a script swaps the view, keyboard\nfocus stays on the link that was clicked, or is lost if the element holding it\nwas removed, and nothing tells assistive technology that a new view has arrived\nunless the page does. Set the title and move focus to the new view's heading,\nas the example does. The Navigation API takes on more of this itself. A\nnavigation handled with `intercept()` resets focus by default, to the first\nelement with `autofocus` or else to the body, and once the handler finishes,\nthe browser signals completion to the user, which the standard says includes\nassistive technology. An app that places focus itself opts out with\n`focusReset: \"manual\"`.\n\n**Everything is paid for up front.** A strict SPA often has to load a large\namount of JavaScript before anything is interactive, and its first data requests\nstart only once that code runs. Split the bundle by route, so that a visitor\ndownloads only what the current view needs, and start the first requests on the\nserver. The Next.js pattern for this fetches data in a Server Component without\nawaiting it and passes the promise to a Client Component, which unwraps it with\n`use()`. Because the request begins before the rest of the app renders, the\nguide says, the response can start streaming at once, and the client is spared a\nwaterfall of requests, each waiting for the one before it.\n\n## Further reading\n\n- [How to build single-page applications with Next.js](https://nextjs.org/docs/app/guides/single-page-applications)\n  — the strict SPA definition, what it costs, and the patterns Next.js uses to\n  keep client-side navigation while moving work to the server.\n- [HTML Standard: The History interface](https://html.spec.whatwg.org/multipage/nav-history-apis.html#the-history-interface)\n  — `pushState()`, `replaceState()` and how session history entries are added\n  and replaced.\n- [HTML Standard: Navigation API](https://html.spec.whatwg.org/multipage/nav-history-apis.html#navigation-api)\n  — the `navigate` event, `intercept()`, and the focus and scroll handling that\n  comes with it.\n- [How to create a static export of your Next.js application](https://nextjs.org/docs/app/guides/static-exports)\n  — one HTML file per route, what a static export cannot do, and serving clean\n  URLs with nginx.\n\n\u003chttps://engineer.company/glossary/single-page-application/\u003e\n","date_modified":"2026-11-09T21:50:25Z","description":"One HTML document that JavaScript rewrites as the reader moves around: the browser APIs behind it, what it costs, and four ways it goes wrong.","formats":{"gemtext":"https://engineer.company/glossary/single-page-application/index.gmi","gopher":"https://engineer.company/glossary/single-page-application/gophermap","html":"https://engineer.company/glossary/single-page-application/","json":"https://engineer.company/glossary/single-page-application/index.json","markdown":"https://engineer.company/glossary/single-page-application/index.md","pdf":"https://engineer.company/glossary/single-page-application/index.pdf"},"kind":"page","language":"en","title":"What is a single-page application?","url":"https://engineer.company/glossary/single-page-application/","version":1}