Routing in a single page app(spa) without framework, just javascript - javascript

I am trying to make a Single Page Application using html, css and javascript. I would like to add some routing to it. I have made server-side rendered websites with nodejs and express. How do I create a routing system for my SPA? Can we use express for client-side routing? If not, are there any alternatives to express for client side routing?

If you don't want to use a framework/library for building a SPA, you have two options
Use a JS routing library ex: navigo, didn't try it myself TBH
Build it by yourself
To build your own simple SPA Routing, first, you need to:
Define routing config, each path with the relevant component/element/content to load
Define your routing root, the element where you will inject the content
Then you have two options:
Use # Hash paths (ex: domain.com/#/messages) with window popstate event, so you can handle this event by getting the hash path and decide which content to inject in the root, check this answer for more details about his approach
Implement a custom routing with normal paths (ex: domain.com/messages), that needs more effort, and to achieve that you need to:
Implement your custom navigation links, where you need to prevent the default behavior of navigation, and do the navigation manually using your custom logic
Use History API, (ex. pushState) to control the location state and the history stack
Adjust your server config to always load index.html
Add your custom logic using the Location API to manage these redirects manually, ie. when a user opens domain.com/messages, it will open index.html, then you need to check manually what the content to load for /messages path and inject it in the root element
Please be aware of the needed time, effort, reliability, maintainability, of each option before starting!

Related

Static data but not for changing api data?

I was creating a blog with nextjs MongoDB and express. I used getStaticProps and getStaticPaths to generate pages dynamically and display each blog on a separate page. but after deployment, if I add or remove a blog from the API then. it is not reflected on the website until the next deployment.
This is the expected behavior when using Next to build a static site. At build time, it's going to use getStaticPaths to generate a list of all the available pages for your blog, and then it will build each one into an html file using getStaticProps data. From that point forward, getStaticPaths and getStaticProps won't run again (they run in development mode, but not when you build and export your site).
So when you delete or add a blog post, the static website doesn't know anything about that because it's just a "dumb" set of html files. You have generally two options:
Set up a build pipeline that listens for changes (add, remove, update) to your blog content and rebuilds your site when the content changes, or
Switch to using Next in SSR mode instead of SSG mode, which would allow you to use getServerSideProps which runs on every page load and which would update immediately as your content changes.
That second one (using SSR) requires you to run your Next site on a node server like Vercel or Firebase Functions or something similar versus how you have it now (SSG) where it's just a bunch of html files and javascript and can be hosted in places like Github pages or Amazon S3.

Use dynamic routes in Nuxt SPA after generating

I'm trying to use dynamic routes in a Nuxt SPA. I know how to use dynamic routes in Universal Mode and I know how to generate them during build time using functions but I'm looking for something where I don't need to re-build with every new entry in a database for instance.
My web-app allows users to create content (via Strapi backend) that should be immediately accessible in a form like www.domain.com/content/uniqe_id (without rebuilding the project)
Is this possible? Can I create something like the /content/index.vue that has access to the parameters and fetch the right content?
On a side-note: I would prefer to use Universal Mode for several reasons, but I'm using Three.js in my project and the only way to get it to work is to use SPA. I've posted about it here
If you are using SPA mode, you don't really need to worry about dynamic routes, as everything is rendered on the client. The only thing you would need to take care of, is setting up your production server to always redirect to your index.html, so you don't get a 404 when accessing other pages.
If you are using Universal you could still generate a SPA fallback for handling your dynamic routes on the client side, by adding this to your nuxt.config.js:
Docs
generate: {
fallback: true,
// ...
},
Using this, Nuxt generates a 404.html which will render the page in SPA mode, instead of showing a 404, while the other routes are generated like normal.
If you want to properly generate all routes and have instant access, you could use this technique to show users a temporary SPA version of your page, until the page is rebuilt.

Dynamically building static websites

I'm building a simple website generator using React, Express/Node and MongoDB.
I built a UI to receive contents and styling params from a multi-step form, and a dashboard where users can manage settings in second place. All the data is saved/fetched in Mongo when needed, using Express. I have a "publish" button in the frontend, which fires a POST to the backend.
Then the related express route fetches the correct data from mongo and pass it to a function, which runs locally a "create-react-app" with a custom template and injects params/content to the right components. After that, it runs a build and deploys the result to a subdomain.
My question is: am I wrong managing to build static files and deploying them every single time the user hits the "publish" button?
Do I need to dynamically generate and serve the site when is requested?
The best and most "react" way to do this would indeed be to dynamically generate and serve the site. It will be a bit more upfront work but will result in better ux.
What you are doing now will be quite slow and not very user friendly.

javascript window.history API on first page load

I am trying to implement a javascript router with window.history API. I've been using ui-router for a long time but I want to create my own router for my smaller apps. Everything looks fine until meeting a problem like this: I am serving my page at localhost:8080/index.html. I am routing in the page with history API related properties. When I click to a route, I lose the index.html part. For example url becomes localhost:8080/home. When I directly try to go to that state, as you expect I get 404 error naturally. How can force to route over index.html to that state?
HTML5 history (pushState, etc) works by rewriting the URL on the client side. Hence it needs the server to also be able to rewrite the URL, and load the same index.html file whatever the URL.
Without this server rewrite, the two possible options are :
Use a hashbang JavaScript router based on URL like /idex.html#!/current/path
Do not use JavaScript for routing, and just rely on server directory structure to serve different file for each endpoint

How do I have a web game run on the same URL?

For rapid prototyping of my concepts, I'm using Express with Mongo and so far have set up a mongostore cookie storage system.
My question: Is it possible, after logging in/authenticating/etc, to have everything occur on the same page, aka '/game'? I still want multiple views and routes to be rendered, but using different areas of the screen, or overwriting elements on the screen, with the base game.jade still visible.
I essentially want to have the user on the same URL the entire time, but still use multiple routes and views. I looked into stuff like '/game/:stuff' but that still changes the URL I think.
FYI this is called a single-page web application.
One common way to do this is to route to different views using the hash token. For example, all of the following URLs would be part of the same page:
/game#introScreen
/game#level1
/game#level2
Your client code can respond to changes in the hash portion of the URL and change the display accordingly. The page does not reload and all your JavaScript code (and variable state) remains in place.
If you're using a framework like angularjs it can help do the routing for you.

Categories