Learn Astro Β· 10/15

Server-Side Rendering (SSR) & Dynamic Astro

7 min read

πŸš€ Server-Side Rendering (SSR) & Dynamic Astro

Welcome back, code traveler! πŸ‘¨β€πŸ’»πŸ‘©β€πŸ’»

Up until now, we’ve been treating Astro like a high-tech printing press. We press the "Build" button, Astro creates a bunch of HTML pages (Static Site Generation), and we hand those papers out to anyone who visits our URL.

But what if you want to greet the user by name? What if you want to show the current price of Bitcoin right this second? What if you want to hide a page behind a login screen?

A printing press can't change the newspaper after it's printed. If you want dynamic, real-time data, you need to stop printing and start streaming.

Welcome to Server-Side Rendering (SSR). Let's turn your static website into a dynamic web application.


1. Static (SSG) vs. Server (SSR) Output Modes

The Definition

Static Site Generation (SSG) happens at Build Time. When you run npm run build, Astro compiles your code into HTML/CSS/JS. When a user requests your site, the server simply hands over these pre-made files.

Server-Side Rendering (SSR) happens at Request Time. The HTML is not generated until a user actually clicks the link to your page. The server builds the page on the fly, specifically for that user, in that moment.

The Problem: The "Generic Greeting" Issue

Imagine you are building a dashboard.

  • With SSG: You build the site. It says "Hello, User." Everyone sees "Hello, User." You cannot access database credentials securely or read the user's browser cookies because the build happened on your computer last Tuesday, not on the user's computer today.

The Solution: On-Demand Rendering

With SSR, when a request hits the server:

  1. The Server wakes up. ⚑
  2. It checks who the user is.
  3. It fetches live data from an API or Database.
  4. It constructs the HTML saying "Hello, Sarah!"
  5. It sends the custom HTML to the browser.

Industry Standard: When to use which?

  • Use SSG (Default) for: Blogs, Documentation, Portfolios, Marketing pages. (Fastest, cheapest).
  • Use SSR for: E-commerce carts, User dashboards, Social media feeds, Analytics.

Fun Fact: Computers are incredibly fast, but SSR is technically slower than SSG because the server has to "think" before sending the page. SSG is like grabbing a burger from the warmer; SSR is like waiting for them to grill the patty.


2. Adding and Configuring an SSR Adapter

The Concept

By default, Astro builds files that can run anywhere (plain HTML). But when you switch to SSR, you need a Server to run that logic on the fly.

Astro doesn't know where you plan to host your app. Are you using a Node.js server? Vercel's serverless functions? Netlify's Edge?

An Adapter is a plugin that translates Astro's SSR code into something your specific hosting provider understands.

The Setup

To enable SSR, you need to update your astro.config.mjs and install an adapter.

The "Hard" Way (Manual Config)

In astro.config.mjs:

javascript
import { defineConfig } from 'astro/config';

export default defineConfig({
  output: 'server', // This turns on SSR
});

The "Easy" Way (Automatic Integration) πŸ› οΈ

Astro has a magical CLI command that installs the adapter, updates your package.json, and configures astro.config.mjs for you.

For Node.js (Standard Server):

bash
npx astro add node

For Vercel:

bash
npx astro add vercel

For Netlify:

bash
npx astro add netlify

Under the Hood

When you run npx astro add vercel, Astro changes your config file to look like this:

javascript
// astro.config.mjs
import { defineConfig } from 'astro/config';
import vercel from '@astrojs/vercel/serverless';

export default defineConfig({
  output: 'server', // Changed from 'static' to 'server'
  adapter: vercel(),
});
  • output: 'server': Tells Astro "Don't build HTML files yet. Build a server app."
  • output: 'hybrid': A cool middle ground. It keeps most pages Static (SSG) but lets you mark specific pages as SSR using export const prerender = false;. This is highly recommended for performance!

3. Working with Astro.request and Astro.response

Now that we are running on a server, we have access to the Request (what the user sent us) and the Response (what we send back).

The Concept

Astro uses the standard Web API Request and Response objects. If you've used fetch in the browser, you already know how this works. This is different from Node/Express frameworks that use their own proprietary objects.

Astro.request

This object contains details about the incoming HTTP request. You use this to read headers, check the URL, or get form data.

Example: detecting the HTTP Method
Inside your .astro frontmatter:

astro
---
// src/pages/contact.astro

let message = "Fill out the form";

if (Astro.request.method === "POST") {
  // The user submitted the form!
  // We can read the data they sent.
  try {
    const data = await Astro.request.formData();
    const name = data.get("username");
    message = `Thanks for posting, ${name}!`;
  } catch (error) {
    console.error(error);
  }
}
---

<h1>{message}</h1>
<form method="POST">
  <input type="text" name="username" required />
  <button>Submit</button>
</form>

Astro.response & Redirects

Sometimes you don't want to show a page; you want to send the user somewhere else (like after a successful login).

The Standard Way (Redirect):

astro
---
if (someCondition) {
  return Astro.redirect('/dashboard');
}
---

The "404" Way:
You can also return a specific Response object to set headers or status codes manually.

astro
---
if (!userIsAdmin) {
  return new Response(null, {
    status: 404,
    statusText: 'Not Found' // Pretend it doesn't exist 🀫
  });
}
---

Imagination Time: Think of Astro.request as an envelope the user hands you. You open it to read the letter inside. Astro.response is the envelope you seal and hand back.


4. Managing Cookies and Basic Authentication Flows

The Definition

Cookies are tiny text files stored in the user's browser. Because HTTP is "stateless" (the server forgets who you are immediately after responding), we use cookies to remind the server "Hey, it's me again."

The Problem

Without cookies, you would have to type your password on every single page click. That would destroy the internet.

The Solution: Astro.cookies

Astro provides a clean utility to read, set, and delete cookies.

Practical Example: A Simple "Login" Gate πŸ”

This isn't bank-grade security (you'd need a real Auth library like Lucia or Auth.js for that), but this explains the mechanism.

1. The Login Logic (login.astro)

astro
---
// If the user clicks "Login", we give them a cookie badge.
if (Astro.request.method === "POST") {
  // Set a cookie named 'user-access'
  // httpOnly: true means JavaScript can't read it (Security best practice!)
  Astro.cookies.set("user-access", "granted", { 
    path: "/",
    httpOnly: true,
    secure: true,
    maxAge: 60 * 60 * 24 // 1 day
  });
  
  return Astro.redirect("/dashboard");
}
---
<form method="POST">
  <button>Log In (Get Cookie)</button>
</form>

2. The Protected Route (dashboard.astro)

astro
---
// Check if the user has the badge
const hasAccess = Astro.cookies.has("user-access");

const cookieValue = Astro.cookies.get("user-access")?.value;

if (!hasAccess || cookieValue !== "granted") {
  // You shall not pass! πŸ§™β€β™‚οΈ
  return Astro.redirect("/login");
}
---

<h1>Welcome to the Secret Dashboard</h1>
<p>You have the cookie!</p>

3. Logging Out
To log out, you simply destroy the cookie.

astro
---
Astro.cookies.delete("user-access", { path: "/" });
return Astro.redirect("/login");
---

Interesting Fact

Did you know cookies have a size limit? It's usually around 4KB. If you try to stuff a whole user profile JSON object into a cookie, the browser might just reject it. Use cookies for IDs and Tokens, not for storing your entire database!


Summary

  1. SSG is for static content (build once). SSR is for dynamic content (build per request).
  2. Use Adapters (npx astro add vercel) to tell Astro where it lives.
  3. Use Hybrid mode (output: 'hybrid') to get the best of both worlds.
  4. Astro.request lets you handle Form POSTs and read headers.
  5. Astro.cookies allows you to build login flows and remember users.

Now go forth and make your static site come alive! ⚑


πŸ“š References & Further Reading

Challenge

You are tasked with creating a function to process data from an e-commerce shopping cart.

Write a JavaScript function named processShoppingCart that takes one argument: an array of product objects.

Each product object has the following structure: { id: number, name: string, price: number, quantity: number, inStock: boolean }.

Your function must perform the following operations in sequence using array methods:

  1. Filter the input array to keep only the products that are currently in stock (where inStock is true).
  2. From the filtered array, create a new array of objects. Each new object should contain only the product's name and a new property called totalValue, which is the result of price multiplied by quantity.
  3. Calculate the grand total by summing up the totalValue of all objects in the array created in the previous step.
  4. Finally, the function should return a single object with two properties:
    • processedProducts: The array of objects created in step 2.
    • grandTotal: The sum calculated in step 3.

Expected result

Your function should correctly process the input array and return an object with the calculated data.

For example, if the productData from the initial code is passed to your function, it should produce the following output object:

json
{
  "processedProducts": [
    { "name": "Laptop", "totalValue": 1200 },
    { "name": "Mouse", "totalValue": 50 },
    { "name": "Monitor", "totalValue": 600 },
    { "name": "Headphones", "totalValue": 150 }
  ],
  "grandTotal": 2000
}

Explanation of the example:

  • The 'Keyboard' and 'Webcam' products are excluded because their inStock property is false.
  • The processedProducts array contains new objects with the name and calculated totalValue for each in-stock item.
  • The grandTotal is the sum of all totalValue properties: 1200 + 50 + 600 + 150 = 2000.
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.