Different SSR server side rendering framework

Different SSR server side rendering framework

all

Server-Side Rendering is a method of loading and parsing frontend elements and codes of web applications on the hosted server itself. Back in the day, browsers were not that advanced and only rendered the content of the HTML documents to present a static version of a web page to users.

The basic idea was to render all the elements on the server so that browsers don’t have to compile much. This was fast and efficient. However, the advent of JavaScript-based frameworks changed the face of rendering frontends altogether.

What Frameworks Support SSR for Web Development?

For fast-loading frontend, it is necessary to deliver essential data and content to the browser. And as mentioned, server-side rendering perfectly does the job. Here are some frameworks with included support for SSR for web software development.

  1. React
  2. Angular Universal
  3. NextJS
  4. NuxtJS
  5. GatsbyJS

Lets talk about all these one by one

We can create our Next.js project with its provided command-line program. To create the project, we just run:

npx create-next-app

or:

yarn create next-app

to create our project.

Then to start the dev server, we run:

npm run dev

Then we go to http://localhost:3000/ and our app.

Now we can create a component in the pages folder to add our page.

We go into the pages folder, create an hello.js file and add:

function Hello() {
  return <div>hello world</div>;
}
export default Hello;

to it.

We’ve to remember to export the component so that it’ll be rendered.

Then we can go to http://localhost:3000/hello and see our page.

Next.js does routing automatically by the file name so we don’t have to worry about that.

Pages with Dynamic Routes If we want to create pages with dynamic routes, we just put them in the folder structure and the URLs will follow the same structure.

For example, we can create a posts folder and create our files.

We create 1.js in pages/posts and write:

function Hello() {
  return <div>hello 1</div>
}
export default Hello
Likewise, we create 2.js in the same folder and write:

function Hello() {
  return <div>hello 2</div>
}
export default Hello

Then when we go to http://localhost:3000/posts/1 and http://localhost:3000/posts/2, we’ll see hello 1 and hello 2 respectively. Pre-rendering Next.js pre-renders every page by default.

The HTML for each page are created in advanced. This is better for performance and SEO than rendering it on the client-side. The pages only come with the JavaScript it needs to load so that it loads faster.

There’re 2 forms of pre-rendering. One is static generation and the other is server-side rendering. Static generation means that HTML is generated at build time and are reused on each request. Since it reuses the pages, it’ll be the fastest way to render pages, so this is the recommended option. The other option is server-side rendering, which renders the HTML no each request.

We can choose between the 2 types of rendering. Static Generation with Data We can generate pages statically with data. To do this, we can write: pages/yesno.js

function YesNo({ data }) {
  return <p>{data.answer}</p>;
}
export async function getStaticProps() {
  const res = await fetch('https://yesno.wtf/api');
  const data = await res.json();
  return {
    props: {
      data,
    },
  };
}
export default YesNo;

We created a new component file with the YesNo component. The getStaticProps function gets the data asynchronously from an API. Then we return the resolved value by return an object with the data in the props property. Then we can get that data from the props in the YesNo component. And in the JSX, we displayed the data.

Next takes care of routing for you.

  • Faster Rendering.
  • Supports typescript, tailwind , APIs .
  • Has SEO (Search Engine Optimization)
  • Has Image Optimization.

Lets compare Next with SvelteKit

//Next.js
npx create-next-app@latest
//SvelteKit
npm init svelte@next my-app

Routing

Routing determines what URL will be needed to access different pages on the website. All three frameworks use file-based routing, which is primarily what all meta-frameworks use. The URL is based on the name and location of the file for that particular page.

Below, you’ll see some examples of how different files get mapped to URLs, including an example with URL params, which define a part of the URL as a variable that you can retrieve.

Next.js

/ → pages/index.js
/hello → pages/hello/index.js or pages/hello.js
/use_param/:id → pages/use_param/[id].js

SvelteKit

/ → src/routes/index.svelte
/hello → src/routes/hello/index.svelte or src/routes/hello.svelte
/use_param/:id → src/routes/use_param/[id].svelte

Loading data on the server-side

A major benefit of using a meta-framework is handling a lot of data preparation prior to your page hydrating, like API calls, transformation, etc. When you use a meta-framework, you don’t have to prepare loaders or things like the useEffect Hook to deal with the asynchronous nature of these issues.

In all three frameworks, there is a function on each page we can define that will be run from the server prior to shipping the page to the user’s browser.

Next.js Similarly, in Next.js, you can export a function called getServerSideProps. The return value can then define the props to the page component:

export const getServerSideProps = async ({ params, query }) => {
  // get a param from the url
  const id = params.id;
  // getting data from the url query string
  const limit = query.limit;

  return { props: { id, limit } };
};

export default function SomePage() {
  let { id, limit } = useLoaderData();
  return (
    <div>
      <h1>The params is: {id}</h1>
      <h1>The limit url query is: {limit}</h1>
    </div>
  );
}

SvelteKit

With SvelteKit, you define a function called load in a separately designated script block. Just like the previous examples, you can handle any API calls and data preparation, then return the data to be used as props to the page component:

<script context="module">
        // Load function to define data
        export function load({ page }) {
   // get params from url
   const id = page.params.id
   // get data from url query
   const limit = page.query.get("limit")
                return {
                        props: {
                                id,
            limit
                        }
                };
        }
</script>

<script>
   // normal client side javascript block
        export let id;
   export let limit
</script>

<div>
   <h1>The params is: {id}</h1>
   <h1>The limit url query is: {limit}</h1>
</div>

Pre-rendering pages as static site generators

Pre-rendering pages as static site generators is probably the biggest diversion in feature sets. At the time of writing, Remix does not support pre-rendering of pages, while Next.js and SvelteKit do, meaning you can also use them as static site generators.

Next.js If you prefer that your page is pre-rendered, simply export getStaticProps instead of getServerSideProps. Otherwise, we’ll observe the same pattern as before.

SvelteKit If you want a page to be pre-rendered in the module script blog, just set the following code:

export const prerender = true; The code above will tell SvelteKit to pre-render the page instead of rendering it on each request.

API Routing

While we can handle logic on the server side with the loader, getServerSideProps, or the load function, API keys and other data shouldn’t be in this code. You may still need dedicated API URLs with code that is only visible and run on the server side.

Next.js If you create a route that exports a route function like in Express.js within the pages/api folder, it will be treated similarly to an API route:

export default function handler(req, res) {
  res.status(200).json({ id: req.params.id });
}

SvelteKit

If you have a JavaScript or TypeScript file instead of a Svelte file, export a function, and it will be treated as an API route. The name of the function will determine what method it is a response to:

export async function get({ params }) {
  return {
    body: { id: params.id },
  };
}

Styling

When it comes to styling, the both frameworks can differ quite a lot.

Next.js You can use the helmet component to add link tags as well, but you can also use styled-components, JSS, Emotion, Sass, or any other CSS abstraction along with just importing standard CSS style sheets.

SvelteKit Svelte, like Vue, uses single-file components, so the CSS is in the components file.

Comments