Server-side Rendering in Solid JS

What is Server-Side Rendering?

Server-side rendering renders your application on the server and then sends the HTML to the client. This is opposed to the client rendering the application of their browser in any other case, called client-side rendering. Server-side rendering has many blessings, but the most essential is that it allows search engines like Google and Yahoo to move slowly through your software and allows your software to be client-agnostic.

Server-side rendering; Source: IONOS


Server-side rendering is right for search engine crawlers because they cannot run Javascript code, so if your software is rendered at the client (browser), then search engines will no longer be capable of moving slowly through your application.

How does Solid implement SSR?

Solid.Js implements SSR in three unique ways, depending on the form of utility you're constructing. The three exclusive methods are:

  • renderToString: This is used to render a factor to a string of HTML.
  • RenderToStringAsync: This is used to render an issue to a string of HTML asynchronously.
  • RenderToStream: This is used to render a factor to a stream of HTML.

How does renderToString work?

The idea behind renderToString is quite simple. It takes in a component and renders it into a string of HTML. The side that is handed in is called a root factor. It renders what it can on the server (elements outside the suspense boundary) and hydrates pinnacle-degree components on the client. Asynchronous data is fetched and rendered to the client without hydration.

renderToString; Source: Frontend Armory


In this form of SSR, the client may be in charge of carrying out fact fetching while the server is in charge of rendering the software. This is referred to as client fetching SSR. This is the most fundamental form of SSR and the easiest to implement.

RenderToString is a function that takes in a thing and renders it to a string of HTML.

import { renderToString } from "solid-js/web";
function App() {
return <h1>Hello World</h1>;
}
const html = renderToString(() => <App />);

The above instance will render the App component as a string of HTML, <h1>Hello World</h1>.. This string of HTML can then be sent to the client and displayed there.

How to use renderToString

To apply renderToString properly, you should have it run on the server. This may be performed by creating a server using one of Node.js's many server frameworks. The most popular one is Express.

import express from "express";
import { renderToString } from "solid-js/web";

function App() {
  return <h1>Hello World</h1>;
}

const app = express();
app.get("/", (req, res) => {
  const html = renderToString(() => <App />);
  res.send(html);
});

app.listen(3000, () => {
  console.log("Server started on port 3000");
});

The above instance will create a server using Express and render the App issue as a string of HTML. This string of HTML will then be sent to the client and displayed there.

What is Async SSR?

Async SSR is a server-side rendering method utilized by most Javascript meta-frameworks like Next.Js, Nuxt.Js, Gatsby, and others. It is a way that lets you render your software on the server and ship the HTML to the client along with the appropriate asynchronous records already fetched. This permits the client to render the page without looking ahead to fetching the statistics.

Async SSR; Source: Wade Zimmerman

Solid.Js gives a similar technique through the use of the renderToStringAsync function. This characteristic permits you to render your utility on the server and ship the HTML to the client along with all the asynchronous information already fetched. This allows your software to be client-agnostic, and you no longer have to worry about fetching client-side data.

How does renderToStringAsync work?

RenderToStringAsync takes a thing and returns a promise that resolves to a string of HTML. This string of HTML is the rendered issue, with all of the asynchronous statistics already fetched and serialized. Therefore, the entire utility is prepared to be hydrated when it reaches the client.

import { renderToStringAsync } from 'solid-js/web'
import {createResource} from 'solid-js'

const App = () => {
  const [data] = createResource(getAsyncData)
  async function getAsyncData() {
  const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
  const json = await response.json()
  return json
}

return (
  <div>
    <h1>Async SSR</h1>
    <p>{data().title}</p>
  </div>
 )
}

renderToStringAsync(App).then(html => {
console.log(html)
})

You'll note that I did not employ a Suspense boundary before accessing the records in the template. In Async SSR, Suspense limitations are not needed because records are prefetched at the server earlier than rendering. The above code will render the App on the server and return to a promise that resolves to HTML as soon as the asynchronous facts have been fetched. The HTML will appear something like this:

<div>
<h1>Async SSR</h1>
<p>delectus aut autem</p>
</div>

How to use renderToStringAsync

To use renderToStringAsync, you may want a server that can run Javascript. You can use any server you need; however, we will use Express for the sake of this situation.

// server.js
import express from 'express'
import { renderToStringAsync } from 'solid-js/web'
import App from './App'
const app = express()

app.get('/', async (req, res) => {
  const html = await renderToStringAsync(() => <App/>)
  res.send(html)
})

app.listen(3000, () => {
  console.log('Server running on port 3000')
})

// App.js
import {createResource} from 'solid-js'
export default function App() {
  const [data] = createResource(() =>      fetch('https://jsonplaceholder.typicode.com/todos/1').then(res =>    
  res.json()))
  return (
    <div>
      <h1>Async SSR</h1>
      <p>{data().title}</p>
    </div>
  )
}

What is streaming?

Streaming is a server-side rendering technique just like Simple server-side rendering, besides using streams. Data is loaded on the server and sent along with the flow so the client can render it.

Streaming; Source: DhiWise

In this method, the most effective preliminary HTML is hydrated in place of Async SSR. Data loading is slightly faster, permitting web page load times to be decreased. This is mainly noticeable compared to Async SSR when used on slow servers.

How does renderToStream work?

RenderToStream works by taking in a thing and returning HTML; however, for any node asynchronous data is wanted, a placeholder is rendered in its location and replaced as part of the stream loads. So in streaming, suspense limitations are rendered and then changed, rather than in async SSR, in which suspense boundaries aren't rendered.

import { renderToStream } from 'solid-js/web'
import { createResource, Suspense } from 'solid-js'
import List from './MyListComponent'
const App = () => {
  const [userData] = createResource(getUserDataAsync)
  const [userPosts] = createResource(getUserPostsAsync)
  return (
    <div>
      <h1>Streaming</h1>
      <Suspense fallback={<p>Loading...</p>}>
        <h2>{userData().username}</h2>
        <Suspense fallback={<p>Loading posts...</p>}>
          <List posts={userPosts()}/>
        </Suspense>
      </Suspense>
   </div>
  )
}
renderToStream(() => <App/>)

The hard-coded example above will render the loading placeholders then replace the nodes as they circulate. Here's a step-by-step explanation of what that could appear to be:

<div>
  <h1>Streaming</h1>
  <p>Loading...</p>
</div>
<div>
  <h1>Streaming</h1>
  <h2>johndoe</h2>
  <p>Loading posts...</p>
</div>
<div>
  <h1>Streaming</h1>
  <h2>johndoe</h2>
  <ul>
    <li><a href='/post/1'>first post</a></li>
    <li><a href='/post/2'>second post</a></li>
    <li><a href='/post/3'>third post</a></li>
    <li><a href='/post/4'>fourth post</a></li>
  </ul>
</div>

How to use renderToStream?

To apply renderToStream you may want a server that can run Javascript code. You may also use any server framework you need, but for the sake of this situation, we can be utilizing Express.

// server.js
import express from 'express'
import { renderToStringAsync } from 'solid-js/web'
import App from './App'
const app = express()

app.get("*",(res,req) => {
  return renderToStream(() => <App/>).pipe(res)
})

app.listen(8080, () => console.log('App is listening on port 8080'))

// App.jsx
import {createResource} from 'solid-js'
export default function App() {
  const [data] = createResource(() =>    fetch('https://jsonplaceholder.typicode.com/todos/1').then(res =>   
  res.json()))
  return (
    <div>
      <h1>Async SSR</h1>
      <p>{data().title}</p>
    </div>
  )
}

SolidJS vs. NextJS

Here is an assessment of SolidJS vs. Next.Js in terms of server-side rendering:

SolidJS:

SolidJS; Source: CSS-Tricks

  • SolidJS presents a dynamic server-side rendering solution that allows a virtually isomorphic improvement using the Resource primitive.
  • SolidJS handles server rendering by compiling JSX templates to extremely efficient string appending code, which can be carried out through the Babel plugin or preset.
  • Solid Start is a collection of plugins that enable client-side and server-side rendering in SolidJS packages.
  • SolidJS implements SSR in three distinct methods depending on the type of utility being constructed: renderToString, renderToStringAsync, and renderToStream.
  • SolidJS has an innovative rendering style sets it apart from nearly every other JavaScript framework nowadays.

Next.JS:

Next.js; Source: Enlear Academy


  • Next.Js affords server-side rendering (SSR), which involves turning in pre-rendered HTML to the client. This technique improves web page load times and reduces the workload the client's browser requires.
  • Next.js is known for its ease of use and readability.
  • Next.Js is an incredible framework for building internet packages with server-side rendering capabilities.

Conclusion

Server-side rendering (SSR) effectively improves the overall performance, SEO, and accessibility of SolidJS packages. SolidJS and Next  Js are wonderful frameworks for constructing web packages with server-side rendering solutions. SolidJS provides a dynamic server-side rendering answer and handles server rendering by compiling JSX templates to ultra-efficient string appending code. Next.Js affords server-side rendering and is thought of for its ease of use and clarity.

While SolidJS has a revolutionary rendering style that sets it apart from almost every other JavaScript framework nowadays, Next.Js is a brilliant framework for building web applications with server-side rendering skills. The choice between SolidJS and Next.Js, in the long run, depends on the precise desires and requirements of the mission, consisting of performance, ease of use, and clarity.



How much is a great User Experience worth to you?


Browsee helps you understand your user's behaviour on your site. It's the next best thing to talking to them.

Browsee Product