This sample demonstrates how to package and serve static web applications (SPAs) as IBM Code Engine functions. It's designed for scenarios where a full Code Engine application is unnecessary: small static bundles, internal tools, previews, demos, or packaged customer-specific frontends.
The function serves static files from a dist/ directory with intelligent routing:
- Direct file serving for existing assets
- Fallback to
index.htmlfor client-side routing - Proper cache headers (long-lived for assets, no-cache for HTML)
- Support for binary files (images, fonts, videos)
- IBM Cloud CLI with Code Engine plugin
- Node.js 18 or later
- A frontend project that builds to static files
.
├── main.js # Function entrypoint
├── package.json # Function package definition
├── build-spa.sh # Build script (runs during deployment)
├── run-angular # Quick-start script for Angular
├── run-react # Quick-start script for React
└── run-svelte # Quick-start script for Svelte
Create and deploy a new Angular, React, or Svelte project:
# For Angular
./run-angular
# For React
./run-react
# For Svelte
./run-svelteEach script creates a new project, builds it, and deploys it as a Code Engine function.
You can create any Single Page Application in this project and develop it locally using your normal workflow (e.g., hot reload, dev server, etc.). Once you're ready to deploy:
- Develop locally - Use your framework's development server and tools as usual
- Test your build - Ensure
npm run buildproduces static files indist/orbuild/ - Deploy - Run the function create or update command to deploy to Code Engine
The build process automatically handles packaging your static files into the function during deployment.
When you deploy to Code Engine, the build process:
- Detects your frontend -
build-spa.shfinds the first non-hidden directory (excludingnode_modulesanddist) - Installs dependencies - Runs
npm ciornpm install - Builds the frontend - Executes
npm run build - Locates output - Finds
index.htmlin eitherdist/orbuild/ - Copies to root - Places build artifacts in root
dist/directory - Cleans up - Removes the source frontend directory
The function package includes only main.js, package.json, and dist/.
The function in main.js:
- Extracts the request path from
__ce_path - Sanitizes the path to prevent directory traversal
- Attempts to serve the requested file directly from
dist/ - Falls back to
index.htmlfor paths without extensions (client-side routing) - Returns 404 for missing asset files
index.html:Cache-Control: no-cache(always check for updates)- All other files:
Cache-Control: public, max-age=31536000(1 year)
This assumes your build process generates content-hashed filenames for assets.
ibmcloud ce function create \
--name my-static-app \
--runtime nodejs-24 \
--build-source .ibmcloud ce function update \
--name my-static-app \
--build-source .ibmcloud ce function get --name my-static-appThe function URL will be in the output under "URL".