Choosing Between HashRouter and BrowserRouter on the Web

A comparison of HashRouter and BrowserRouter in SPA apps, including URL forms, server configuration, anchor behavior, form submissions, and how SPA routing works.

Feb 5, 2021 · 1 min read · 212 Words · -Views -Comments · Programming
WebShell 🇨🇳 阅读中文版
Read with AI

Choose an AI assistant

ChatGPT Open in a new tab with the article link and prompt
Claude Copy the prompt, then open Claude

Open Claude
Trouble reading the article?

If the prompt is missing, copy the full prompt below into your AI assistant. If the AI cannot read the article, paste the visible passage you want to discuss and add your question.

In SPA apps, frontend routing typically uses either HashRouter or BrowserRouter. Each has pros and cons. Here’s a summary.

HashRouter vs BrowserRouter

  1. URL form differs: HashRouter uses URL hashes (e.g., https://1991421.cn#posts) while BrowserRouter uses traditional paths (e.g., https://1991421.cn/posts).

  2. BrowserRouter needs some server setup since users may refresh on a deep URL, which hits the server. Ensure all SPA routes serve the host page. HashRouter doesn’t need this.

    app.get('*', function (req, res) {
      res.sendFile(path.join(__dirname + '/index.html'));
    });
    
  3. With HashRouter, in-page anchors can complicate things. For a URL like https://1991421.cn/#posts/detail/1234567#comment, location.hash is #posts/detail/1234567#comment; you’ll need to parse it yourself to get the final anchor.

  4. With HashRouter, the hash portion isn’t included in form submissions.

Conclusion

  • Both have trade-offs. Choose based on needs.
  • If either works, BrowserRouter is generally preferable: no hash-related form/anchor quirks. Just remember the server config.

How SPA Routing Works

  • BrowserRouter uses the HTML5 History API to change URLs and track state.

    • history.pushState pushes a new state into the session history and updates the location bar.
  • HashRouter uses location.hash to change URLs and track state.

    • onhashchange listens for hash changes.

Note: Both are client-side; URL changes don’t reload the page.

Final Thoughts

Frontend routers exist to swap content based on the URL. The routing “registration” mechanism is provided by the frontend—nothing more.

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover