Server-Side Rendering with Next.js and TypeScript
Static Generation vs Server-Side Rendering
Before we jump into the code, let me explain what Static Generation and Server-Side Rendering are.
Static Generation means generating static HTML files at build time. This is the best approach for building a fast website. Static HTML files are faster than Server-Side Rendering and good for search engines. It is good for pages that don't frequently update and are publicly available.
Server-Side Rendering means generating the HTML on each request. The server generates the output for each incoming request. The server will fetch the data from the external API or the database. This process is the reason why it is slower than Static Generation. We also need to scale the server if requests grow. SSR is good for pages that frequently update or for websites that are handled by CMS (Content Management System).
Why Server-Side Rendering?
The completed code can be found at https://github.com/aristorinjuang/next-server-side. Let me explain only the important parts here.
You can find the code above in
getServerSideProps to send properties to the
Home function for each request. I fetched the data from the external API using Axios in this example. You can change it to fetch data from the database too.
The result JSON from the Simple REST API here is a little unusual. It is a
Map instead of an
Article. You can change it to your own.
pages/[id].tsx. It made the routing to be
/<id>. Still use
getServerSideProps to fetch data for each request, but I use
catch here. I printed the error in the stdout or terminal and returned
undefined. So, if the article is
undefined, I can return the custom 404 page.
I created a custom 404 page in
pages/404.tsxinstead of using the built-in 404 page,
import Error from 'next/error'. So, my 404 page has the same layout as the blog post.
- Next.js vs Hugo
- Test-Driven Development
- Simple REST API with TypeScript
- TypeScript Crash Course
- Atomic Design with React