This tutorial shows you how to use Gemini for Google Cloud for Google Cloud, an AI-powered collaborator in Google Cloud, to explore, create, modify, test, and deploy a sample Node.js app.
For the following steps, consider that you're a Node.js developer and you want to write a simple web application in JavaScript that uses a basic form. In this scenario, you'll use the Express framework for the app and the EJS templates for the HTML form.
This guide is intended for Node.js developers who are looking to use Gemini to speed up the development process. It assumes you are familiar with basic cloud concepts, though not necessarily Google Cloud.
Objectives
This tutorial helps you learn how to use Gemini to do the following:
- Develop a Node.js web app in Cloud Shell.
- Author unit tests for your Node.js web app.
- Deploy your Node.js web app to Cloud Run.
Google Cloud products used
This tutorial uses the following Google Cloud products:
- Gemini: An always-on collaborator in Google Cloud that offers generative AI-powered assistance to a wide range of users, including developers and data scientists. To provide an integrated assistance experience, Gemini is embedded in many Google Cloud products.
- Cloud Code for Cloud Shell plugin: An IDE plugin extension that provides development cycle support for apps that will run on Google Cloud.
- Cloud Run: A fully-managed service that lets you build and deploy containerized apps. Google Cloud handles scaling and other infrastructure tasks so that you can focus on the business logic of your code. For pricing information, see the Cloud Run pricing page, and use the Pricing Calculator to generate a cost estimate based on your projected usage.
Before you begin
- Create a Google Cloud project if you don't have an existing Google Cloud project that can be used for this tutorial.
- Activate Cloud Shell.
- Ensure that Gemini is set up for your Google Cloud user account and project.
- Enable Gemini for Cloud Shell by selecting the project that has been granted access to Gemini features.
Prompt Gemini to generate Node.js code
Gemini can help you generate Node.js code based on the prompts you provide in the chat and the descriptions you write in the code comments. The more code you write and the more context you provide to Gemini, the better Gemini can assist you in developing your app. Note that the responses from Gemini can vary depending on how you ask questions or describe the context, so it is a good practice to review Gemini's responses before accepting the suggestions during the development process.
Before asking Gemini to help generate starter code, use the Cloud Shell Terminal to create an empty directory, and add two empty files.
mkdir node-js-with-gemini
cd node-js-with-gemini
touch app.js test.js
In the Cloud Shell Editor, select content_copy Explorer and open the folder you just created in the Cloud Shell Terminal.
Install packages
You know that you'd like to install the express
and ejs
packages for your
Node.js app. To ask Gemini for help on installing these
packages, follow these steps:
In the left-side panel in the Cloud Shell Editor, click spark Gemini.
In the Gemini pane, enter a prompt like:
What is the command to install express and ejs packages for node.js?
Click send Send.
Gemini returns a response that will be similar to the following:
To install the express and ejs packages for Node.js, you can use the following command:
npm install express ejs
Copy the command provided by Gemini and run it in your Cloud Shell Terminal.
Author application files
After installing the packages, use Gemini for guidance on how to
add the installed packages in your app.js
file.
- Open your
app.js
file in the Cloud Shell Editor. In the Gemini chat, enter a prompt like:
How do I add these packages to my app.js file?
Gemini's response will be similar to the following:
To add the express and ejs packages to your app.js file, you can use the following code:
const express = require('express'); const ejs = require('ejs');
This will require the express and ejs packages and make them available to use in your app.js file.
Add the code provided by Gemini to your
app.js
file.
Generate code with comments
The Cloud Code plugin has a feature that lets Gemini use file comments to generate code. For example, when you add a comment as a placeholder in your file, you can prompt Gemini to generate code as described in the comment.
To use this feature in your app.js
file, ensure Gemini is
enabled in the Cloud Shell Editor.
At the end of the file, add a comment placeholder to initialize the web app. For example:
// Initialize express web app using ejs templating engine
Move your text cursor to the end of the comment, and press
Control+Enter
(for Windows and Linux) orControl+Return
(for MacOS), then press tab to use Gemini's code generation capabilities to generate code.Gemini's response will have two lines of code below the comment, similar to the following:
// Initialize express web app using ejs templating engine const app = express(); app.set('view engine', 'ejs');
If the code generation output is different from what you expected, modify or delete the extra content as you see fit.
Next, add more comments to generate the base capabilities for your Express web app.
Go to the bottom of the
app.js
file, and add the following comments:// add urlencoded middleware to parse form data // define the home route // create a /greeting POST route with a `name` parameter // create a /greeting route that accepts a name parameter // start the server on port 8080
Generate code for each file comment similar to how you generated code before.
Before you accept the suggestions, review the generated code for accuracy.
The comments in your
app.js
file should now be accompanied with corresponding code, similar to the following:// add urlencoded middleware to parse form data app.use(express.urlencoded({ extended: true })); // define the home route app.get('/', (req, res) => { res.render('index'); }); // create a /greeting POST route with a `name` parameter app.post('/greeting', (req, res) => { const name = req.body.name || 'World'; res.render('greeting', { name }); }); // start the server const port = process.env.PORT || 8080; app.listen(port, () => { console.log(`App listening on port ${port}`); console.log('Press Ctrl+C to quit.'); }); // create a /greeting route that accepts a name parameter app.get('/greeting/:name', (req, res) => { res.render('greeting', { name: req.params.name }); });
Create a package.json file
After the code has been generated for your base application, create and add
content to the package.json
file.
- Create a
package.json
file in the same directory as yourapp.js
file. In the Cloud Shell Editor, select spark Gemini and enter a prompt like:
Based on my app.js file, can you create a package.json file?
Gemini's response should suggest the start script and dependencies to specify, and will be similar to the following:
Sure. Here is a package.json file that you can use with your app.js file:
{ "name": "my-app", "version": "1.0.0", "description": "A simple Node.js web app using Express and EJS.", "main": "app.js", "scripts": { "start": "node app.js" }, "dependencies": { "express": "^4.17.1", "ejs": "^3.1.6" } }
This package.json file includes the following information:
The name of the app (my-app)
The version of the app (1.0.0)
A description of the app (A simple Node.js web app using Express and EJS.)
The main file of the app (app.js)
The scripts that can be run on the app (start)
The dependencies of the app (express and ejs)Copy and paste only the contents provided by Gemini into your
package.json
file.
Create ejs templates
To finish up your web app, create a views
directory for your ejs
templates
in the same directory as your app.js
and package.json
files.
In your terminal, enter the following:
mkdir views touch views/index.ejs views/greeting.ejs
Open the
index.ejs
file in the editor and paste the following:<html> <body> <form action="/greeting" method="post"> <label for="name">What's your name?</label> <input type="text" id="name" name="name" autofocus /> <button type="submit">Submit</button> </form> </body> </html>
Open the
greeting.ejs
file in the editor and paste the following:<html> <body> <a href="/">Home</a> <p>Hello <%= name %>~</p> </body> </html>
Preview your app in a browser
With your app code, templates, and requirements all completed, you can now confirm if your app works.
Run the following command to install the dependencies.
npm install
Run the following command to start the app:
npm start
Confirm the app works. Select the Web Preview button located on the top right of the Cloud Shell taskbar. Then, select the port number from the displayed menu. Cloud Shell opens the preview URL in a new browser window.
Write unit tests
After confirming that your Node.js app works, you can write unit tests in your
test.js
file before deploying your app to Cloud Run. In the
following example, you'll ask Gemini for assistance in
generating a unit test for when the HTTP response code is 200.
At the bottom of your
app.js
file, add the following line to export your app file.module.exports = app;
Open your
test.js
file.To test when the response returns an HTTP 200 status code, open the Gemini chat pane and enter a prompt like:
Can you generate a unit test for my home route in app.js to assert that the response code is 200?
Gemini should respond with something similar to the following:
Sure. Here is a unit test for the home route in app.js that ensures the response code is 200:
const assert = require('assert'); const request = require('supertest'); const app = require('./app.js'); describe('GET /', () => { it('should return a 200 response code', async () => { const response = await request(app).get('/'); assert.equal(response.status, 200); }); });
This test checks that the home route returns a status code of 200.
Add the suggested code block to your
test.js
file.Install the mocha test and supertest packages by running the following command in your terminal:
npm i mocha supertest
Update your
package.json
file to include your new test script and its packages. For example:{ "name": "my-app", "version": "1.0.0", "description": "A simple Node.js web app using Express and EJS.", "main": "app.js", "scripts": { "start": "node app.js", "test": "mocha" }, "dependencies": { "express": "^4.17.1", "ejs": "^3.1.6", "mocha": "^10.2.0", "supertest": "^6.3.3" } }
Run the following command to run the tests:
npm test
Your test should show as passing if there are no errors. If you want to add
additional tests for your other routes, continue to ask Gemini
for suggestions to add to your test.js
file.
Deploy to Cloud Run
With your app now running locally, you can proceed with deploying to Google Cloud. Cloud Run works well for this scenario because you can deploy from source code and not have to manage any infrastructure when running your app.
In the Gemini chat, ask Gemini how to deploy to Cloud Run directly from your source code using gcloud:
What is the gcloud command for deploying a Cloud Run service from source code?
Gemini should respond with something similar to:
You can deploy directly to Cloud Run from your source code in your current directory using gcloud. To do this, you can use the
gcloud run deploy
command with the--source flag
. This flag tells gcloud to use your source code to build a container image and deploy it to Cloud Run.For example, to deploy the code in your app.js file to Cloud Run, you would use the following command:
gcloud run deploy app --source .
This command will build a container image from your app.js file and deploy it to Cloud Run.
You can also use the --region flag to specify the region where you want to deploy your app. For example, to deploy your app to the us-central1 region, you would use the following command:
gcloud run deploy app --source . --region us-central1
For more information on deploying to Cloud Run from source code, you can see the Cloud Run documentation.
Use the gcloud command that Gemini provided in the response.
Follow the prompts for selecting a region and select the option to allow unauthenticated invocations for your test app. After the app is deployed successfully, the output will return a Service URL.
Clean up
To avoid incurring charges to your Google Cloud account for the resources used in this tutorial, you can delete the Google Cloud project that you created for this tutorial. Alternatively, you can delete the individual resources.
- Caution: Deleting a project has the following effects:
- Everything in the project is deleted. If you used an existing project for the tasks in this document, when you delete it, you also delete any other work you've done in the project.
- Custom project IDs are lost. When you created this project, you might have created a custom project ID that you want to use in the future. To preserve the URLs that use the project ID, such as an appspot.com URL, delete selected resources inside the project instead of deleting the whole project.
If you plan to explore multiple architectures, tutorials, or quickstarts, reusing projects can help you avoid exceeding project quota limits.In the Google Cloud console, go to the Manage resources page.
In the project list, select the project that you want to delete, and then click Delete.
In the dialog, type the project ID, and then click Shut down to delete the project.
What's next
- Read the Gemini for Google Cloud overview.
- Understand Gemini quotas and limits and supported locations.
- Learn more about deploying from source code using Cloud Run.