Hosting Next.js Application
Next.js is a React framework that supports server-side rendering (SSR). This article describes how to host Next.js applications on cloud development.
Step 1: Initialize Project
Use the CLI tool to initialize a CloudBase project.
cloudbase init
Select language Node
, select template Hello World
cloudbase init
? Select the associated environment xxx - [xxx-xxx]
? Please enter project name cloudbase-next
? Select template language Node
? Select Cloud Development template Hello World
✔ Project cloudbase-next created successfully!
Enter the project root directory:
cd cloudbase-next
Then create a Next.js application in the functions/next
directory:
npm init next-app functions/next
Step 2: Configure the project
We will now make some modifications to the next project to meet the requirements for deployment inside a cloud function.
Enter the next root directory
cd functions/next
Install serverless-http
npm install --save serverless-http
Then add the following file to functions/next/index.js
// index.js
const next = require("next");
const serverless = require("serverless-http");
const app = next({ dev: false });
const handle = app.getRequestHandler();
exports.main = async function (...args) {
await app.prepare();
return serverless((req, res) => {
handle(req, res);
})(...args);
};
Add the following file to functions/next/next.config.js
:
// next.config.js
module.exports = {
assetPrefix: "/next"
};
Step 3: Build and Release
We run in the functions/next
directory
npm run build
Then return to the project root directory and run
cloudbase fn deploy next
Use the default configuration when publishing.
cloudbase fn deploy next
? No function publish configuration found, use the default configuration? Yes
✔ [next] Function deployed successfully!
Then we create an HTTP service route:
cloudbase service create -f next -p next
Then we can access the Next.js application via URL.
cloudbase service create -f next -p next
✔ Cloud Function HTTP service created successfully!
https://${env-id}.service.tcloudbase.com/next