LaunchFast Logo LaunchFast

API Routes in Angular 18 Server Side Rendering

Rishi Raj Jain
Injecting Environment Variables Dynamically in Cloudflare Pages

In this guide, you will learn how to define and use API routes in a server-side rendered Angular 18 application.

Prerequisites

You’ll need the following:

Table Of Contents

  • TODO

Create a new Angular Application

Let’s get started by creating a new Angular project. Execute the following commands:

npm i -g @angular/cli@latest
ng new angular-ssr-api-routes

ng new is the recommended way to scaffold an Angular project quickly.

When prompted, choose:

  • CSS for the stylesheet format
  • y for enabling Server-Side Rendering (SSR) and Static Site Generation (SSR/Prerendering)

Once that is done, move into the project directory and start the app in development mode by executing the following command:

cd angular-ssr-api-routes
npm run start

The app should be running on localhost:4200.

In angular.json, set prerender to false so that the application is always server-side rendered.

In server.ts, add the following code to create an API route at /api/data:

// File: server.ts

// ...

// Example Express Rest API endpoints
// server.get('/api/**', (req, res) => { });
// Serve static files from /browser
server.get('**', express.static(browserDistFolder, {
    maxAge: '1y',
    index: 'index.html',
}));

server.get('/api/data', (req, res) => { 
    res.json({ code: 1 }); 
}) 

// ...

Make the following additions to app.config.ts in the src/app directory to include HttpClient using fetch:

// File: app.config.ts

import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';
import { provideRouter } from '@angular/router';

import { routes } from './app.routes';
import { provideClientHydration } from '@angular/platform-browser';
import { provideHttpClient, withFetch } from '@angular/common/http'; 

export const appConfig: ApplicationConfig = {
  providers: [
    provideZoneChangeDetection({ eventCoalescing: true }),
    provideRouter(routes),
    provideClientHydration(),
    provideHttpClient(withFetch()), 
  ],
};

Update the app.component.ts in the src/app directory to fetch from the API route:

// File: app.component.ts

import { isPlatformBrowser } from '@angular/common'; 
import { Component, Inject, OnInit, PLATFORM_ID } from '@angular/core'; 
import { RouterOutlet } from '@angular/router';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css',
})
export class AppComponent implements OnInit {
  isBrowser: boolean; 
  title = 'with-angular';
  constructor(@Inject(PLATFORM_ID) platformId: Object) { 
    this.isBrowser = isPlatformBrowser(platformId); 
  } 
  async ngOnInit() { 
    if (this.isBrowser) { 
      const fetchCall = await fetch('/api/data'); 
      const fetchResp = await fetchCall.json(); 
      // Do something
    } 
  } 
}

In one terminal:

npm run watch

In another terminal:

npm run serve:ssr:angular-ssr-api-routes

Now, let’s close the developement server to create API routes.

Conclusion

In this guide, you learned how to inject environment variables dynamically in Cloudflare Pages.

If you have any questions or comments, feel free to reach out to me on Twitter.

Learn More Create a Telegram Bot in Next.js App Router: A Step-by-Step Guide → Injecting Environment Variables Dynamically in Cloudflare Pages → Using Unplugin Icons in Next.js: A Step-by-Step Guide →