0
0
AstroHow-ToBeginner ยท 4 min read

How to Use Adapter for SSR in Astro: Setup and Example

To use an adapter for SSR in Astro, install the adapter package for your target environment, then configure it in astro.config.mjs under the adapter field. This enables Astro to build your site for server-side rendering on platforms like Node.js or Cloudflare Workers.
๐Ÿ“

Syntax

In your astro.config.mjs, import the adapter package and add it to the adapter property inside the exported config object.

This tells Astro how to build and deploy your SSR site for a specific environment.

  • import adapter from '@astrojs/adapter-node': imports the Node.js adapter.
  • export default { adapter: adapter() }: sets the adapter in the config.
javascript
import adapter from '@astrojs/adapter-node';

export default {
  adapter: adapter(),
};
๐Ÿ’ป

Example

This example shows how to set up Astro with the Node.js adapter for SSR. It includes the config file and a simple page that renders server-side.

javascript
import adapter from '@astrojs/adapter-node';

export default {
  adapter: adapter(),
  // Optional: specify output directory
  outDir: 'dist',
};

---
// src/pages/index.astro
const time = new Date().toLocaleTimeString();
---
<html lang="en">
  <head>
    <title>SSR Astro Example</title>
  </head>
  <body>
    <h1>Hello from Astro SSR!</h1>
    <p>Current server time: {time}</p>
  </body>
</html>
Output
<html lang="en"> <head> <title>SSR Astro Example</title> </head> <body> <h1>Hello from Astro SSR!</h1> <p>Current server time: 10:30:45 AM</p> </body> </html>
โš ๏ธ

Common Pitfalls

  • Forgetting to install the adapter package with npm install @astrojs/adapter-node or the adapter for your platform.
  • Not importing the adapter correctly in astro.config.mjs.
  • Using an adapter incompatible with your deployment environment.
  • Missing the adapter field in the config, which disables SSR.

Always check the adapter docs for platform-specific setup.

javascript
/* Wrong: Missing adapter import and config */
export default {
  // No adapter set - SSR won't work
};

/* Right: Proper adapter import and config */
import adapter from '@astrojs/adapter-node';

export default {
  adapter: adapter(),
};
๐Ÿ“Š

Quick Reference

StepDescription
Install adapterRun npm install for your target adapter package
Import adapterImport the adapter in astro.config.mjs
Configure adapterSet the adapter property to adapter() in config
Build siteRun astro build to generate SSR output
DeployDeploy the output to your server or platform
โœ…

Key Takeaways

Install and import the correct adapter package for your SSR target platform.
Set the adapter in astro.config.mjs to enable SSR builds.
Adapters customize Astro's build output for different server environments.
Check adapter docs for platform-specific requirements and options.
Without an adapter, Astro defaults to static site generation, not SSR.