Router History vs. Hash Mode: URL Style and Server Setup
Router history mode determines your SPA's URL style. History mode uses clean URLs (`/users`) but needs server setup, while hash mode uses a hash symbol (`/#/users`) and works out-of-the-box.
WHY IT EXISTS: Single-Page Applications (SPAs) need a way to map browser URL changes to view changes without a full page reload. The browser's History API and URL hash fragments are the two primary mechanisms for this, leading to different router modes with distinct trade-offs in aesthetics, SEO, and server configuration.
THE MENTAL MODEL: Think of it as a contract between your client-side app and your server. With "history mode," the server must promise to always serve your SPA's entrypoint (index.html) for any unknown path. With "hash mode," the client promises to only use the part of the URL after the '#', which the browser never sends to the server, requiring no special server contract.
HOW IT WORKS: History mode uses the browser's history.pushState API to change the URL without a page refresh. The URL looks clean (e.g., app.com/profile). The browser treats this as a real path, so on refresh, it requests /profile from the server. Hash mode puts the application path in the URL's hash fragment (e.g., app.com/#/profile). Browsers do not send the hash fragment to the server. The server only ever sees a request for app.com/, serves index.html, and the client-side router reads the hash to display the correct view.
WHEN TO USE IT: Use history mode when you want clean, user-friendly URLs, need good SEO, and have control over your server configuration to set up the necessary fallback route. This is the recommended modern approach. Use hash mode for simple deployments on static hosts where you cannot configure server-side redirects or for legacy applications where changing server config is not feasible.
WHEN NOT TO USE IT: Avoid history mode if you cannot configure your web server, as it will break direct navigation and page refreshes. Avoid hash mode if SEO is a primary concern or if the '#' in the URL is considered aesthetically unpleasing for your brand.
ONE CANONICAL EXAMPLE: A user is on myapp.com/users/123. In history mode, if they hit refresh, the browser requests the /users/123 path from the server. Without a fallback rule, the server returns a 404. With a fallback, it serves index.html, the app loads, and the client-side router displays the user 123 profile. In hash mode, the URL would be myapp.com/#/users/123. On refresh, the browser only requests /, the server sends index.html, and the router correctly shows the user profile.
Read the original → router.vuejs.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.