tRPC - Server Rendering
by Tomas Trescak· tRPC

Root Folder
Not Attempted
NameProgress
Introduction
Not Read
🍰 Player
Not Read
Setup
Not Attempted
NameProgress
Software Installation
Not Read
Project Setup
Not Read
Running and Testing
Not Read
React and ReactDOM
Not Read
💡 Assignment 1: Welcome Message
Not Attempted
Submissions
Not Read
React
Not Attempted
NameProgress
JSX and Components
Not Read
Props
Not Read
👾 Exercise: Props
Not Attempted
CSS Styles
Not Read
useState and Hooks
Not Read
👾 Exercise: useState
Not Attempted
Conditional Rendering
Not Read
Lists
Not Read
👾 Exercise: Lists
Not Attempted
Forms and Events
Not Read
👾 Exercise: Forms
Not Attempted
💡 Assignment 2: Front End
Not Attempted
Advanced React
Not Attempted
NameProgress
Pure Components - memo
Not Read
Lifecycle - useEffect
Not Read
Expensive? - useMemo
Not Read
DOM Interactions - useRef
Not Read
forwardRef
Not Read
useImperativeHandle
Not Read
👾 useImperativeHandle
Not Attempted
Context
Not Read
useCallback
Not Read
useId
Not Read
useReducer
Not Read
Infrastructure
Not Attempted
NameProgress
Database
Not Read
NextAuth and Github Authentication
Not Read
Prisma and ORM
Not Read
Project Setup
Not Read
Project Authentication
Not Read
APIs
Not Attempted
NameProgress
APIs
Not Read
APIs - Slides
Not Attempted
Rest APIs
Not Read
Rest APIs - Express.js
Not Read
ReastAPIs - Next.js
Not Read
Securing APIs
Not Read
Securing APIs - NextAuth
Not Read
tRPC
tRPC - Routers
tRPC - Server Rendering
tRPC - Client Rendering
Persisting Data
Assignment 3: APIs
0 / 50 XP

In Next, you have two options for how to deliver our pages to our clients. We can either use client-side rendering or server-side rendering. We will delve into individual differences in an advanced course, but for now you need to remember the following:

Client-Side Rendering

  • Nothing is rendered on the server
  • Server sends:
    • the static HTML code 
    • all javascript files
  • Application is rendered on the client sending requests for any data that javascript requires
  • While the application is waiting for data, the “Loading …” migh appear
  • Fast-ish, but very unfriendly to bots
  • A LOT of javascript might be sent to the client, reducing page load times

Server-Side Rendering

  • Application is pre-rendered on the server
  • Server sends
    • the generated HTML code
    • all javascript files
    • all the data for the initial page load
  • Client instantly sees the pre-rendered web-page without pesky “Loading …”
  • Client re-renders the page, adding javascript functionality to add interactivity
  • Fast-ish, but increases load on your server
  • Bots love this!
  • Still, a LOT of javascript is sent to the user

Server Components

Recently, React came with “Server Components”. This complements server-side rendering with the fact that these components are not re-rendered on the client, and only their HRML is sent to the browser. Consequently, there is no longer a need to send any javascript that this component needs.

tRPC in Server-Side Rendering

Your project comes pre-configured with tRPC functionality for both client-side rendering and server-side rendering. Let's test the server-side rendering now! 

First, let's add some artificial wait time on the “tasks” route handler to spot the differences. In your src/server/api/routers/tasks.ts, router, please modify the tasks handler to include artificial wait time:

  tasks: protectedProcedure.query(async ({ ctx, input }) => {
    // wait for three seconds
    await new Promise((resolve) => setTimeout(resolve, 3000));
    return tasks.filter((task) => task.userId === ctx.session.user.id);
  }),

Second, explore the TaskList component in the src/components/task-list.tsx file. Please note that this component is defined as async as per below. Only a Server Component can be asynchronous. Trying to use asynchronous components on the client (in browser) would immediately lead to an error!

 export async function TaskList() {
    ...

To use tRPC API on server, we need to import it from src/trpc/server. Please add the following line to the top of your file:

import { api } from "~/trpc/server";

Then, in your component, you can use the API method directly to load your data!

export async function TaskList() {
  // Fetched tasks from server
  const session = await getServerAuthSession();
  const tasks = session ? await api.tasks.tasks() : [];
  ...

How beautiful is this! A single, type-safe function call instead of using those pesky type-unsafe fetch commands. Please run your project and test the server call. You could also get rid of that check for the user and instead make the procedure public. That is up to you.

THE THREE SECOND PROBLEM

When we are loading the page, we are waiting three seconds, for the initial page load. That is a lot! Let's fix that. Next, supports component streaming, which allows to send partial rendering results. To enable sending parts of the UI to client, we wrap the long-running asynchronous code in Suspense. In your src/app/page.tsx file, wrap the task list in Suspense such as the following.

import { Suspense } from "react"; // <- Add this import

export default async function Home() {
  ...
  <Suspense fallback={<div>Loading posts...</div>}>
     <TaskList />
  </Suspense>

When you refresh the page now, you can see that the page was immediately loaded with “Loading Tasks …” message. Much better user experience! 

👾 Side Exercise

If you do not have any tasks displaying, use your Database Management tool (or prisma studio by running pnpm db:studio) to check for id of your user and use that id to create the initial tasks. 

Prisma DB Studio showing the User table

Then, use that id to create the initial data. In my case, it would be

const tasks = [
  {
    userId: "clum1bkki000014eimfus6n2f", // <- ID of my user
    id: 1,
    description: "Complete the project report",
    completed: false
  },
  { userId: "clum1bkki000014eimfus6n2f", id: 2, description: "Clean the house", completed: true }
];

 

Maggie

Discuss with Maggie
Use the power of generative AI to interact with course content

Discussion

0 comments
Loading editor ...
Remember to be polite and report any undesirable behaviour

Category

Empty

Labels

Discussion has no labels

1 participant

user avatar

Priority

Notifications

You're not receiving notifications from this thread.
Course Outline