Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

On-demand rendering

By default Astro builds all pages ahead of time. On-demand rendering (also called SSR) means the page is generated on the server every time it is opened. You need it for search, the visitor's personal data and forms. This mode requires an adapter, a package that runs the built site on a particular platform: Node.js, Netlify, Vercel or Cloudflare.

The Node.js adapter

npx astro add node

The command installs @astrojs/node and adds it to astro.config.mjs:

// astro.config.mjs
import { defineConfig } from 'astro/config';
import node from '@astrojs/node';
 
export default defineConfig({
  adapter: node({ mode: 'standalone' }),
});

The standalone mode means the build runs as a self-contained server. All pages are still built ahead of time; the adapter only lets individual pages opt out of that.

An on-demand page

Create a search page, src/pages/search.astro:

---
export const prerender = false;
 
const query = Astro.url.searchParams.get('q') ?? '';
---
 
<h1>Search</h1>
<form>
  <input name="q" value={query} />
  <button>Search</button>
</form>
{query && <p>You searched for: {query}</p>}

The line export const prerender = false turns off prebuilding for this page. Open /search?q=astro and the page says "You searched for: astro". Change the address and the answer changes: the page is computed again for every request.

What is available on the server

PropertyWhat it holds
Astro.urlThe full request address, including the parameters after ?
Astro.paramsDynamic route parameters
Astro.requestThe request object: method, headers, body
Astro.cookiesReading and setting cookies
Astro.redirect('/login')Returns a redirect to another address

For example, Astro.cookies.get('theme')?.value reads a theme cookie, and return Astro.redirect('/') in the frontmatter sends the visitor to the home page.

The whole site on demand

If most pages are like this, change the default: output: 'server' in defineConfig. Then all pages are rendered on demand, and those that should be prebuilt are marked with export const prerender = true.

SettingPages by default
no output (static)Built ahead of time
output: 'server'Rendered on demand

Common mistake

People write export const prerender = false but do not add an adapter. The build stops with an error saying server pages need an adapter. First run npx astro add with the right platform, then turn off prebuilding for pages.

Thanks for reading!

Donate to the site — we work hard for you.