Astro and Express: SSR in Astro
Tags: astro, express
Published: 2024-05-22 07:49:43

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:

   ```bash
   npm create astro@latest
   ```

   Follow the prompts to create your new project.

 2. **Enable SSR with:

```bash
npx astro add node
```

3. **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:

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

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

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:
```bash
npm install express
```


**Step 2: Set Up the Express Server**

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

```javascript
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}`);
});
```

**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:

```bash
npm run startserver
```

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

```bash
// Make the fetch request to the local API endpoint
const response = await fetch('http://localhost:3000/api/people')
const data = await response.json()
```

- Add inside html the follwing code

```bash
    <ul>
      {
        data.map((person) => (
          <li id={person.name}>
            {person.name} {person.lastName} - {person.address}
          </li>
        ))
      }
    </ul>
```

You Havet to build again the astro project

```bash
npm run build
npm run serve

```

Run `npm run startserver`

![alt text](https://eneaslari.com/daf03974-41cc-4063-a6fc-eee323a45a20.png "new image file")

And congratulation you just implemented ssr with astro

![alt text](https://eneaslari.com/6dd59567-376e-450e-b7ab-47d2ecaaf2e5.png "new image file")