Server⁠-⁠side Rendering

Server-side Rendering, aka SSR, can be enabled in Astro. When you enable SSR you can:

  • Implement sessions for login state in your app.
  • Render data from an API called dynamically with fetch.
  • Deploy your site to a host using an adapter.

To get started, enable SSR features in development mode with the output: server configuration option:

astro.config.mjs
import { defineConfig } from 'astro/config';

export default defineConfig({
  output: 'server'
});

When it’s time to deploy an SSR project, you also need to add an adapter. This is because SSR requires a server runtime: the environment that runs your server-side code. Each adapter allows Astro to output a script that runs your project on a specific runtime.

The following adapters are available today with more to come in the future:

You can add any of the official adapters with the following astro add command. This will install the adapter and make the appropriate changes to your astro.config.mjs file in one step. For example, to install the Netlify adapter, run:

npx astro add netlify

You can also add an adapter manually by installing the package and updating astro.config.mjs yourself. (See the links above for adapter-specific instructions to complete the following two steps to enable SSR.) Using my-adapter as an example placeholder, the instructions will look something like:

  1. Install the adapter to your project dependencies using your preferred package manager:

    npm install @astrojs/my-adapter
  2. Add the adapter to your astro.config.mjs file’s import and default export:

    astro.config.mjs
    import { defineConfig } from 'astro/config';
    import myAdapter from '@astrojs/my-adapter';
    
    export default defineConfig({
      output: 'server',
      adapter: myAdapter(),
    });

Astro will remain a static-site generator by default. But once you enable a server-side rendering adapter, every route in your pages directory defaults to a server-rendered route and a few new features become available to you.

Added in: astro@2.0.0 New

To enable hybrid rendering, any page or server endpoint that supports exporting variables (.astro, .mdx, .ts, or .js) can opt-in to prerendering. These files will be statically rendered at build-time, similar to the default static output mode.

Simply add export const prerender = true:

src/pages/mypage.astro
---
export const prerender = true;
// ...
---
<html>
  <!-- Page here... -->
</html>
src/pages/mypage.mdx
---
layout: '../layouts/markdown.astro'
title: 'My page'
---
export const prerender = true;

# This is my page
src/pages/myendpoint.js
export const prerender = true;

export async function get() {
  return {
    body: JSON.stringify({ message: `This is my endpoint` }),
  };
}

The headers for the request are available on Astro.request.headers. It is a Headers object, a Map-like object where you can retrieve headers such as the cookie.

src/pages/index.astro
---
const cookie = Astro.request.headers.get('cookie');
// ...
---
<html>
  <!-- Page here... -->
</html>

This is a utility to read and modify a single cookie. It allows you to check, set, get and delete a cookie.

See more details about Astro.cookies and the AstroCookie type in the API reference.

The example below updates the value of a cookie for a page view counter.

src/pages/index.astro
---
let counter = 0

if(Astro.cookies.has("counter")){
  const cookie = Astro.cookies.get("counter")
  counter = cookie.number() + 1
}

Astro.cookies.set("counter",counter)

---
<html>
  <h1>Counter = {counter}</h1>
</html>

On the Astro global, this method allows you to redirect to another page. You might do this after checking if the user is logged in by getting their session from a cookie.

src/pages/account.astro
---
import { isLoggedIn } from '../utils';

const cookie = Astro.request.headers.get('cookie');

// If the user is not logged in, redirect them to the login page
if (!isLoggedIn(cookie)) {
  return Astro.redirect('/login');
}
---
<html>
  <!-- Page here... -->
</html>

You can also return a Response from any page. You might do this to return a 404 on a dynamic page after looking up an id in the database.

src/pages/[id].astro
---
import { getProduct } from '../api';

const product = await getProduct(Astro.params.id);

// No product found
if (!product) {
  return new Response(null, {
    status: 404,
    statusText: 'Not found'
  });
}
---
<html>
  <!-- Page here... -->
</html>

A server endpoint, also known as an API route, is a .js or .ts file within the src/pages folder that takes a Request and returns a Response. A powerful feature of SSR, API routes are able to securely execute code on the server side. To learn more, see our Endpoints Guide.