APP ROUTER
In the world of SAPUI5/OpenUI5, understanding the role of an App Router, particularly in the context of SAP BTP, is key. Before delving into the distinctions between Standalone and Managed App Routers, it’s crucial to understand the fundamental concept of an App Router.
The @SAP/approuter is used to route requests to different microservices or applications within the SAP Cloud Platform. It’s essentially a Node.js application that acts as a gateway, managing authentication, authorization, and routing requests to different destinations.
What is an App Router?
In the context of SAPUI5, the @sap/approuter package is part of the SAP Cloud Platform and is designed to function as a lightweight application router. It’s essentially a Node.js library that helps you set up a simple server to route incoming requests to the appropriate destinations based on defined routes and configurations.
The @SAP/approuter is a Node.js module that helps you manage routing in a cloud application. It handles tasks such as:
- Serving static content
- Proxying requests to backend services
- Managing authentication and authorization
- Routing requests based on the URL path
Key features of @sap/approuter include:
- Routing: The approuter allows you to define routes that determine how incoming requests are handled. You can specify different routes for different paths, enabling you to direct traffic to different services or destinations.
- Authentication: The router supports authentication and authorization mechanisms, helping you secure your applications. It can integrate with identity providers and handle authentication for your application.
- Single Sign-On (SSO): It supports Single Sign-On, allowing users to authenticate once and access multiple applications without having to log in again.
- Proxy: The approuter can act as a proxy, forwarding requests to backend services while handling authentication and authorization.
- Configuration: You can configure the approuter through a xs-app.json file, where you define routes, authentication methods, and other settings.
Setting Up @SAP/approuter:
Here’s a step-by-step guide to setting up the @SAP/approuter in your project.
Step 1: Install @SAP/approuter
First, you need to install the @SAP/approuter package in your project. You can do this using npm:
npm install @SAP/approuter
Step 2: Create a Configuration File
Create a xs-app.json file to define the routes and other configurations.
{
“welcomeFile”: “/index.html”,
“authenticationMethod”: “none”,
“routes”: [
{
“source”: “^/service/(.*)$”,
“destination”: “backend”,
“csrfProtection”: false
},
{
“source”: “^(.*)$”,
“localDir”: “resources”
}
]
}
- welcomeFile: specifies the default file to be served.
- authenticationMethod: specifies the method of authentication.
- Routes: define how different paths are handled.
Step 3: Create a Server File
The server.js file is used to start the @SAP/approuter application and configure it to serve your application. Here’s an example and an explanation of a basic server.js file for an SAP Cloud Platform application using @SAP/approuter.
Create a server.js file to start the approuter.
const approuter = require(‘@sap/approuter’);
const ar = approuter();
ar.start();
Explanation:
Import the @SAP/approuter Module:
const approuter = require(‘@sap/approuter’);
This line imports the @SAP/approuter module, which is necessary for creating and starting the app router.
Create an App Router Instance:
const ar = approuter();
This line creates an instance of the app router. The approuter function initializes the app router with the configuration provided in the xs-app.json file and other environment settings.
Start the App Router:
ar.start();
Adding Middleware for Custom Logic (Optional)
You might want to add custom middleware for logging, error handling, or other purposes. Here’s an example of how to extend the basic server.js file with custom middleware:
const approuter = require(‘@sap/approuter’);
const express = require(‘express’);
const ar = approuter();
const app = express();
app.use(‘/my-custom-path’, (req, res, next) => {
console.log(‘Custom middleware executed’);
next();
});
// Use app router as middleware
app.use(ar);
// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send(‘Something broke!’);
});
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`App router listening on port ${port}`);
});
Explanation of Extended server.js:
Import Required Modules:
const approuter = require(‘@sap/approuter’);
const express = require(‘express’);
In addition to @SAP/approuter, we import the Express module to create an Express application for adding custom middleware.
Create Instances:
const ar = approuter();
const app = express();
We create an instance of the app router and an Express application.
Add Custom Middleware:
app.use(‘/my-custom-path’, (req, res, next) => {
console.log(‘Custom middleware executed’);
next();
});
This custom middleware logs a message whenever a request is made to /my-custom-path.
Use App Router as Middleware:
app.use(ar);
The app router is used as middleware in the Express application, handling routing as defined in the xs-app.json file.
Error Handling Middleware:
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send(‘Something broke!’);
});
This middleware handles errors by logging the error stack and sending a 500 status response.
Start the Server:
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`App router listening on port ${port}`);
});
The Express application listens on a specified port (defaulting to 3000 if not set in the environment variables).
Step 4: Define Destinations
In the default-env.json file, define the destinations for routing.
The default-env.json file is used to define environment variables and configurations for your SAP Cloud Platform application, including destinations that the app router will use to route requests. Here’s an example of a default-env.json file:
{
“VCAP_SERVICES”: {
“xsuaa”: [
{
“name”: “my-xsuaa-service”,
“label”: “xsuaa”,
“tags”: [
“xsuaa”
],
“plan”: “application”,
“credentials”: {
“clientid”: “your-client-id”,
“clientsecret”: “your-client-secret”,
“url”: “https://your-xsuaa-service.authentication.eu10.hana.ondemand.com“,
“identityzone”: “your-identity-zone”,
“identityzoneid”: “your-identity-zone-id”,
“tenantmode”: “dedicated”,
“sburl”: “https://your-xsuaa-service.authentication.eu10.hana.ondemand.com“,
“uaadomain”: “authentication.eu10.hana.ondemand.com”,
“verificationkey”: “your-verification-key”,
“xsappname”: “your-xs-app-name”
}
}
],
“destination”: [
{
“name”: “backend”,
“label”: “destination”,
“tags”: [
“destination”,
“conn”,
“http”
],
“plan”: “lite”,
“credentials”: {
“clientid”: “your-destination-client-id”,
“clientsecret”: “your-destination-client-secret”,
“uri”: “https://your-destination-service.example.com“
}
}
]
},
“destinations”: [
{
“name”: “backend”,
“url”: “https://my-backend-service.example.com“,
“forwardAuthToken”: true
}
],
“VCAP_APPLICATION”: {
“application_id”: “your-application-id”,
“application_name”: “your-application-name”,
“application_uris”: [
“your-application-uri”
],
“application_version”: “your-application-version”,
“space_id”: “your-space-id”,
“space_name”: “your-space-name”,
“organization_id”: “your-organization-id”,
“organization_name”: “your-organization-name”
}
}
Explanation
- VCAP_SERVICES: Contains information about bound services, such as XSUAA (for authentication) and destination service instances.
- xsuaa: Specifies the XSUAA service instance used for authentication.
- destination: Specifies the destination service instance used for routing requests.
- destinations: Contains the list of destinations used by the app router to route requests.
- name: The name of the destination.
- url: The URL of the backend service.
- forwardAuthToken: Indicates whether the auth token should be forwarded to the destination.
- VCAP_APPLICATION: Contains information about the application instance, such as ID, name, URIs, version, space, and organization.
Usage in xs-app.json
The destinations defined in the default-env.json file are referenced in the xs-app.json file for routing purposes. For example:
{
“welcomeFile”: “/index.html”,
“authenticationMethod”: “none”,
“routes”: [
{
“source”: “^/service/(.*)$”,
“destination”: “backend”,
“csrfProtection”: false
},
{
“source”: “^(.*)$”,
“localDir”: “resources”
}
]
}
In this example, the route with the source ^/service/(.*)$ is routed to the destination named backend, which is defined in the default-env.json file.
Step 5: Run the App Router
Start the app router by running the server.js file.
node server.js
Example Directory Structure
my-app/
│
├── resources/
│ ├── index.html
│ └── … (other static files)
│
├── server.js
├── xs-app.json
└── default-env.json
Summary
The @SAP/approuter package provides a lightweight application router for managing routing, authentication, and authorization in SAP Cloud Platform applications. It acts as a gateway, directing incoming requests to the appropriate backend services or serving static content. By configuring routes in the xs-app.json file and defining destinations in the default-env.json file, you can set up a flexible and powerful routing mechanism for your cloud applications.
Types of App Routers:
- Managed App Router: Offered as a service by SAP BTP, the Managed App Router extends its responsibility to routing requests for all applications within a subaccount.
- Standalone App Router: A standalone app router is not tightly coupled to the SAP BTP environment. You can configure a standalone app router based on the specific needs of your application. You have the flexibility to define specific settings including routes, authentication methods, and more. This type of router is deployed within a Cloud Foundry space and is responsible for managing the routing of requests for all applications in that space.
Comparing Standalone and Managed App Routers:
The main difference lies primarily in management and control:
- Managed App Router: Managed app router is managed by SAP. This means that SAP takes care of provisioning and maintaining the app router, and those users do not need to worry about any of the underlying infrastructure.
- Standalone App Router: Standalone App Router provides greater control, flexibility, and customization. The maintenance of a Standalone App Router are the responsibility of the user or the organization. This involves handling setup, configuration, updates, and troubleshooting.
Feature |
Standalone App Router |
Managed App Router |
Provisioning |
User’s Responsibility |
Handled by SAP |
Maintenance |
User’s Responsibility |
Handled by SAP |
Scalability |
User-Implemented |
Inherent Scalability |
Availability |
Manual Setup Required |
Built-in High Availability |
When to use Managed App Router vs. Standalone App Router:
Managed App Router: Ideal for most use cases due to ease of use, high availability, and scalability.- Standalone App Router: Better suited for specific requirements like custom routing logic or multi-tenant applications, particularly in custom or non-SAP environments.