Search code examples
javascriptnode.jsexpressejsserver-side-rendering

Server side rendering for single page application?


Is it possible to use server side rendering, like EJS, in a single page application? The application is a website that needs to stay on the same page all the time and is not allowed to reload. The app is built mostly around webgl but there is some dynamic html as well.

On the server, I have the following code:

server.get('/test', (req, res) => {
  res.render('test') // test refers to an ejs file
});

If I type in localhost:3000/test manually in the browser or use location.assign('/test') the page is refreshed and I can see the content of the ejs file. But if the content is retrieved through a fetch request or a XMLHttpRequest it seems I have to manually update the html with client-side javascript. Is there a way to get around this?

If the rendering operations needs to be performed manually on the frontend I guess I have no use for EJS in this case.


Solution

  • Is it possible to use server side rendering, like EJS, in a single page application?

    Plenty of SPAs use SSR. It means that they can use the history API and have real URLs giving pages that are search engine friendly, good to fall over to when the client-side JS fails for any reason, and which load quickly (as opposed to loading a skeleton HTML document to bootstrap client-side code which then has to make further Ajax requests).

    But if the content is retrieved through a fetch request or a XMLHttpRequest I have to manually update the html with client-side javascript. Is there a way to get around this?

    Not as such.

    If you want to be able to render pages on the server-side and the client-side then you need both client- and server-side code to do that.

    Most sites using this sort of technique use isomorphic JS and frameworks (such as Next.js) which take care of the heavy lifting.