How to remove "#" in svelte spa router? - web

I use svelte-spa-router npm module for the router of my svelte project.
When using this module it adds "#" in the URL in default to denote it is the spa router.
Such as "localhost:5000/#/app/.." I want to remove this "#" and make the router as the whole router such as "localhost:5000/app" Could anybody help me with this, please?

This is not possible with svelte-spa-router. This package is a hash-based router, and the "#" is key to how this type of router works. From the package docs:
With hash-based routing, navigation is possible thanks to storing the current view in the part of the URL after #, called "hash" or "fragment".
For example, if your SPA is in a static file called index.html, your URLs for navigating within the app look something like index.html#/profile, index.html#/book/42, etc. (The index.html part can usually be omitted for the index file, so you can just create URLs that look like http://example.com/#/profile).
When I created this component, other routers for Svelte 3 implemented navigation using the HTML5 history API. While those URLs look nicer (e.g. you can actually navigate to http://example.com/profile), they are not ideal for static Single Page Applications. In order for users to be able to share links or even just refresh the page, you are required to have a server on the backend processing the request, and building fully-static apps is much harder as a consequence.
Hash-based routing is simpler, works well even without a server, and it's generally better suited for static SPAs, especially when SEO isn't a concern, as is the case when the app requires authentication. Many popular apps use hash-based routing, including GMail!
If you want your URL to not have a "#", you will need to switch to a HTML5 history-based router such as svelte-routing or routify.

Related

How to serve SPA in one separate route in Express multipage app?

Let's say I have a blog and it's a normal Express multipage app. Now I would like to have a blog content manager as SPA with Vue.js.
I want to serve this app from a single route e.g. https://myapp/admin/dashboard
while the rest is a plain multipage express app (same server).
How to setup something like this in express and vue?
There are three possible strategies:
either you serve everything under a common path to the SPA with something like
app.get("/spa/*", spa);
app.get("/spa", spa);
In this case the client-side app will have to know its prefix because it will have to prefix all its links, ie it will have to send you to /spa when it wants to send you home. Both Vue and React Router support this via an option.
either you use URL fragments, ie hash links of the form /spa#sublink
In this case Express sees a single route:
app.get("/spa", spa);
The application doesn't need to know its prefix, you can relocate it, it always sends you to a relative link like href="#sublink. The downside is that you can't have multiple levels.
or you use query arguments like /spa?item=sublink
This is probably the worst way to do it, since it combines the downsides of all other methods
If you are not sure, the second method is probably the way to go - it doesn't require any special setup.

What is the difference between these two ways of serving React App?

I would like to serve a react project from the nodejs server. I encountered the two ways of doing it:
The first way is to use express to serve just the build folder for whatever the req made:
const express = require('express')
const app = express()
const path = require('path')
app.use(express.static(path.join(__dirname,'build')))
app.get('*',function(req,res){
res.sendFile(path.join(__dirname,'build','index.html'))
})
module.exports = app;
The second way is one using ReactDOM.hydrate and ReactDOMServer.renderToString to serve the app. It is described here.
What is best way to achieve the good SEO from the above mentioned ways and when to choose one over other?
Thank you!!!
CSR
The first approach, where you just serve the build folder and direct all the requests to index.html is a default way of how single-page applications (SPA) work. This approach is called Client Side Rendering (CSR), meaning that client (browser) will be responsible for preparing all the content of your website via executing javascript code of your application, then fetch all the data from API (news, posts, profile, etc.) and, finally, build the page layout and display everything on the screen.
SSR
In turn, with the second approach you mentioned, server prepares (renders) the whole document (HTML) with content and sends it to the client which only needs to display it. This is called Server Side Rendering (SSR) and in your case the ReactDOMServer is responsible for that. However, since you want your application to be interactive, you need to "revive" it with javascript (in our case with React) and that is what ReactDOM.hydrate actually does. It appends all the necessary event listeners to existing markup and makes page to behave in the way it would behave if it was fully rendered on the client (default CSR).
SEO
There is a general opinion that using CSR has a bad impact on SEO because bots crawling the site need to perform additional steps (execute javascript) and it slows down the process and make it less efficient, moreover, not all the bots can run javascript at all.
However, nowadays, modern crawlers (e.g. Google) can cope with SPA quite good, but the end results might be not as good as with SSR.
If you are at the beginning of project development and SEO is really a very high priority for you, then you should choose SSR.
However, instead of implementing everything yourself with ReactDOMServer and hydrate, I'd recommend you to take a look at the Next.js - it is powerful and easy to learn React framework.
P.S.
SSG
You also should be aware of the Static Site Generation (SSG) approach, where every single page of your application gets prerendered at the build stage, producing bunch of HTML files and other assets of your site. Then, all those static files are served from a simple hosting and/or CDN. The main benefits of such approach are: very high speed of page loading, great SEO and usually very low cost for maintenance.
However, this approach suits only sites where content changes very rarely and pages are not interactive. Of course, you may combine it with hydration, but it often leads to quite tricky and buggy solutions in the end.
You can read more details about all three approaches here.
React renders on the client side by default. Most search engine bots however, cannot read JavaScript. Therefore, using server-side rendering is better for SEO, because it generates a static HTML file on the server, which is then served to the client.
Another difference is that client-side rendering will take longer to load the first time, but all consecutive times it will render faster (if the client didn't disable cache). A server-side rendered website has to render the page everytime it loads on the server. Making it slightly slower on average, but will provide consistent loading speeds and a faster first-time loading speed which is important for business landing pages as an example.

What is the benefit of serving react app(front end) from express app(back end)

I have developed and hosted few react applications but I'm still confused about the word server side rendering. So, I'm curious to know what is the benefit of serving my react applications from an express server.
Thank you as I look forward to your response.
Please consider clarifying your question, because I don't know also if you use next.js or nuxt.js.
Angular, React, Vue.js are JavaScript frontend frameworks/libraries, which means they are using JavaScript language.
The websites on the Internet contain HTML, CSS, JavaScript Vanilla code.
The application you developed using React.js needs to use React.js library source code, and then you need the React.js code to be compiled to JavaScript Vanilla code because the browser at the end needs a JavaScript native code that it can read.
When I need to see your hosted website, I need to write the domain name to see it, so the HTTP request at the end goes to the server which is hosting your react app, thus if your react application contains just a static content, for example, a landing HTML page, then there is no need for server-side rendering from Express(Node.js), Ruby, PHP, Java,...
What I mean by static content is content that doesn’t change in response to different users, all of them will get the same content.
Notice you can host a static website in Github and you still don't need any server-side rendering...
Let's have a small application for a better explanation:
If you developed a Portfolio that contains a description of yourself, images of your projects, skills, then here there is no need for a server-side rendering.
But if you developed a system that lets a user who has permission to create a short link from a full URL, then you need a backend server(like Java, Ruby, C#, PHP,...) to host the logic code in order to generate a tiny URL from the full URL, and then save it in a Database, that way any user can click the generated tiny URL then this request goes to your backend server which needs to redirect the user with correct full URL, an application like this cannot be done using React.js alone, you need a server to handle the logic.
Returning to your answering your question: "So, I'm curious to know what is the benefit of serving my react applications from an express server."
If you have static content you can avoid using Express, but if you think your application needs some backend logic in the future, then Express or any other backend framework will help you in that.
*Notice when you have a static website, and you tried to edit the content of it, the users which already visited your website, their browser might cached your website content unless (they disabled this option in their browser), so if your website is cached in users' browsers they might not get the updated content unless you changed the static website file name for example by adding ?092130123 to file name in order to let the users' browser download the updated data

A Best Approach of Creating Two Front-End Websites With A Same Base-End

Working on a new project, I need to create two sets of the front end with a same back-end code base and data. The second set of front end can be accessed through a sub-domain name such as secondfrontend.mywebsite.com. What will be the best approach between two sets of front end codes and two basic pages of the single page applications? I am going to use Vue for the front end as it is the simplest Javascript framework in the current JHispter project.
You can consume the JHipster REST API from any consumer you want (SPA, native mobile, ...). Since you have 2 webapps and not written in Angular, you would probably serve them from another http server than the Spring Boot app as static contents (lots of solutions there depending on your infra. Eg: Apache/Nginx, CloudFront, Express, ...). Note : If the fronts and the back are not on the same domain, you will have to take care of setting the CORS accordingly in the Jhipster app.
Also note that JHipster does a lot of optimizations when serving the static content (gzip, set caching headers, ...) so you will have to reproduce these optimizations in your server if you want optimal performance.
For this kind of expansion, I would definitely use a REST API with some sort of load balancing/caching sitting just before the entry point of backend. For sub domain, Cross Site Origin (CORS) should be able to take care of your problem.
Although, I have never used JHipster, but Spring with RestController that serve as rest API is a very nice option if you are working with very large backend. Just bare in mind that Spring Security takes in a urlencoded HTTP Body (Although through some Added filter JSON can also be parse in).
Vue as a front end is also a very nice option for SPA.

Mostly static express app with one server side route

I have an application that I'm developing using express that is almost a purely static site, with the exception of two forms that are posted to the server (a contact form and a request form). The site has roughly 10 static pages and two server side routes to accept the form submission.
I started developing the front end of the application with jade, stylus, and coffeescript, using grunt as both a development server and a build tool to output a production ready version (concat, min, etc..) of all these static assets.
Now onto the two server side routes. I'm curious what peoples thoughts are on this situation, where the app contains 90% static HTML, with only one or two server side routes.
So far I've considered three options:
Option #1: Purely static HTML and "outsource" the two forms to someone like Wufoo
This would eliminate the need for express altogether in production. I could continue to use grunt to build the application. However, I don't like this approach since I wouldn't have total control over the form submission. Not to mention, the number of form submissions with a free account is limited.
Option #2: Purely server-side using express and Jade
I don't like this approach either since I would define 10 or so server side routes, all of which simply render a jade template. Isn't that overkill? My routes would be littered with app.get() calls that contain a single res.render() in the callback. Also, even though we're probably talking milliseconds, why include middleware on pages that don't require it?
Option #3: Mix of #1 and #2, using the express.static() middleware
For this option, I would use something like grunt-express. This is my favorite option, however it seems a little "dirty" to mix client and server side jade templates. What I mean by this is that the express app would have (two) server side routes that are responsible for rendering a jade template. Mixing this with a call to express.static() that points to a directory that contains static HTML files that have been compiled from jade seems a little "dirty" to me. I'm not sure why.
If I choose option #3, how would my grunt build script work? Preferably, I would like the build to output a dist/ folder which contained a production ready express app, including my tiny little app.js file.
Any thoughts are greatly appreciated!
Option #2
res.render(...) is very smart
It will not generate HTML again (if you do not change res.locals)
Beside that render has smart cache control, it will send "304 Not Modified" to browsers, instead of whole body.
Just use Option #2, and make sure browsers get 304 for static content. If you just a newbie to nodejs, make sure you start your node in 'production' mode, because jade is slow in 'development'.
You can render all the server side templates with something like
app.get('/:template', function (req, res) {
res.render(req.params.template);
});

Resources