DEV Community

Cover image for Astro and Express: SSR in Astro
EneasLari
EneasLari

Posted on • Originally published at eneaslari.com

Astro and Express: SSR in Astro

Implementing Server-Side Rendering (SSR) with Astro JS is a great way to improve performance and SEO for your web applications. Astro is designed to support SSR out of the box, making it relatively straightforward to set up. Here’s a basic guide on how to implement SSR with Astro:

  1. Setup Your Astro Project: If you haven’t already created an Astro project, you can start by setting one up. Run the following commands in your terminal:
   npm create astro@latest
Enter fullscreen mode Exit fullscreen mode

Follow the prompts to create your new project.

  1. **Enable SSR with:
npx astro add node
Enter fullscreen mode Exit fullscreen mode
  1. Configure SSR in Astro: By default, Astro projects are configured to render statically. To enable SSR, you’ll need to modify the astro.config.mjs file:
   import { defineConfig } from 'astro/config';

   export default defineConfig({
     output: 'server',
     adapter: {
       name: name: '@astrojs/node',
       // options here
     },
   });
Enter fullscreen mode Exit fullscreen mode

Now lets create an Express server that serves data from a JSON file containing a list of people with their names, last names, and addresses, you'll follow these steps:

Step 1:At the root of your astro project Install Express

Install Express using npm:

npm install express
Enter fullscreen mode Exit fullscreen mode

Step 2: Set Up the Express Server

Create a file named server.mjs in your project directory and add the following code:

import express from 'express';
import { handler as astroHandler } from './dist/server/entry.mjs';

const app = express();
const PORT = 3000;

app.get('/api/people', (req, res) => {
    res.json([
        { name: "John", lastName: "Doe", address: "1234 Main St" },
        { name: "Jane", lastName: "Doe", address: "1235 Main St" },
        { name: "Jim", lastName: "Beam", address: "1236 Main St" }
    ]);
});
// Use Astro handler for all other routes
app.use(astroHandler);

app.listen(PORT, () => {
    console.log(`Server running at http://localhost:${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode

Step 3: Run Your Server

Add "startserver": "node server.mjs" script at package.json

To start the server, run the following command in your terminal:

npm run startserver
Enter fullscreen mode Exit fullscreen mode

You should see the output indicating that the server is running on http://localhost:3000. You can now visit http://localhost:3000/people in your web browser or a tool like Postman to see the JSON data being served.

This configuration uses the astroHandler, which is exported by the built Astro app, to handle requests that aren’t caught by the earlier Express route (/api/people). This allows you to use Express for APIs or other server-specific tasks while Astro handles the SSR and other routes.

Edit index.astro to fetch our data from the server and render them at page

// Make the fetch request to the local API endpoint
const response = await fetch('http://localhost:3000/api/people')
const data = await response.json()
Enter fullscreen mode Exit fullscreen mode
  • Add inside html the follwing code
    <ul>
      {
        data.map((person) => (
          <li id={person.name}>
            {person.name} {person.lastName} - {person.address}
          </li>
        ))
      }
    </ul>
Enter fullscreen mode Exit fullscreen mode

You Havet to build again the astro project

npm run build
npm run serve

Enter fullscreen mode Exit fullscreen mode

Run npm run startserver

alt text

And congratulation you just implemented ssr with astro

alt text

Top comments (0)