2024-09-09 web, development, javascript
Nodejs and Google App Engine
By O. Wolfson
Google App Engine is a fully-managed serverless platform that allows developers to build, deploy, and scale applications without the need to manage infrastructure. It supports multiple programming languages, including Node.js, and provides a variety of tools and services to help developers focus on building their applications. In this tutorial, we will walk through the steps to deploy a "Hello World" Node.js application on Google App Engine, highlighting its key features and benefits along the way.
Tutorial
Create a new directory for your project and navigate to it in the terminal.
Initialize a new Node.js project using npm by running the following command in the terminal:
bashnpm init
You will be prompted to enter some information about your project, such as the name and version. You can accept the default values for most of the prompts by pressing Enter.
Install the express package by running the following command in the terminal:
bashnpm install express
Create a new file called app.js in your project directory and add the following code to it:
javascriptconst express = require("express");
const app = express();
app.get("/", (req, res) => {
res.send("Hello World!");
});
const port = process.env.PORT || 8080;
app.listen(port, () => {
console.log(`App listening on port ${port}`);
});
This code creates a new Express app that listens for HTTP requests on the root URL (/). When a request is made, the app sends the string "Hello World!" as the response.
Create a new file called app.yaml in your project directory and add the following code to it:
yamlruntime: nodejs16
handlers:
- url: /
script: auto
This file tells App Engine to use the Node.js 16 runtime and to route all requests to the root URL (/) to your app.
Initialize a new Git repository in your project directory and commit your code by running the following commands in the terminal:
bashgit init
git add .
git commit -m "Initial commit"
Create a new project in the Google Cloud Console and enable the App Engine API for it.
Install the Google Cloud SDK by following the instructions at https://cloud.google.com/sdk/docs/install.
Authenticate the SDK by running the following command in the terminal and following the prompts:
bashgcloud auth login
Set your default project by running the following command in the terminal and replacing PROJECT_ID with your project's ID:
bashgcloud config set project PROJECT_ID
Deploy your app to App Engine by running the following command in the terminal:
gcloud app deploy
This will upload your code to Google Cloud Storage and deploy it to App Engine. It may take a few minutes for the deployment to complete.
Visit your app in the browser by running the following command in the terminal:
bashgcloud app browse
This will open your app in a new browser window. You should see the message "Hello World!" displayed on the page.