Google Gemini (foundational model) & NodeJS/Express in Webstorm
By following these steps (or similar), you can develop a full-stack Node.js Express + React application that integrates Google's Gemini API, using Google Cloud educational credits in WebStorm.
1. Redeem Educational Credits
Redeem Google Cloud educational credits by following the instructions provided in your email
2. Set Up a Google Cloud Project
Each student should create a new project in the Google Cloud Console.
3. Enable Billing
Link the redeemed educational credits to the project by setting up billing. This is necessary to access services beyond the free tier, including the Gemini API.
4. Enable the Gemini API
Within the project, enable the Gemini API by navigating to the Gemini for Google Cloud page and clicking "Enable."
5. Obtain an API Key
Generate an API key for the Gemini API through the Google AI Studio. This key will be used to authenticate requests from the Node.js application.
6. Develop a Node.js Express + React Application in WebStorm
Step 1: Create a New Node.js Express + React Project (OR OPEN Existing one)
- Open WebStorm.
- Click File > New > Project.
- Select "Node.js Express App" as the project type.
- Choose a project location and click Create.
Eventually you will want to create a directory structure that is MVC focused and may look like the following:
my-project/
│── backend/ <-- The backend folder (Node.js + Express)
│ ├── node_modules/
│ ├── .env <-- Stores API keys (e.g., Gemini API key)
│ ├── package.json <-- Lists dependencies for backend (Express, dotenv, cors, etc.)
│ ├── server.js <-- Main Express server file
│ ├── routes/ <-- Folder for API route files
│ │ ├── geminiRoutes.js
│ ├── controllers/ <-- Optional folder for handling API logic
│ │ ├── geminiController.js
│ ├── models/ <-- Optional folder for database models (MongoDB, PostgreSQL, etc.)
│
│── frontend/ <-- The frontend folder (React)
│ ├── node_modules/
│ ├── public/
│ ├── src/
│ │ ├── App.js <-- Main React component
│ │ ├── index.js
│ ├── package.json <-- Lists dependencies for frontend (React, Axios, etc.)
│
│── package.json <-- Root package.json (if using a monorepo setup)
│── README.md
- Open Terminal in WebStorm (View > Tool Windows > Terminal).
- In the terminal, navigate to the backend folder (where Express is set up) and install required dependencies:
This installs:// In the terminal, run: npm install @google/generative-ai dotenv cors express
- @google/generative-ai: The official Google Gemini API SDK.
- dotenv: A package to securely manage API keys using environment variables.
- cors: Middleware to enable cross-origin requests.
- express: A Node.js framework to handle server-side logic
What is dotenv?
The dotenv module allows developers to store sensitive configuration data, such as API keys, in a .env file instead of hardcoding them in the code. This improves security and simplifies configuration management.
- Security: Keeps API keys and credentials out of the source code.
- Flexibility: Easily switch environments (development, testing, production) with different configurations.
- Convenience: Environment variables can be accessed anywhere in the project.
What is cors?
The cors module is middleware that enables Cross-Origin Resource Sharing (CORS). This is necessary when making API calls from a frontend application running on a different domain (e.g., http://localhost:3000 for React and http://localhost:5000 for Express).
- Why is it needed? Browsers enforce the Same-Origin Policy, preventing requests from different origins by default.
- How does cors() help? It allows requests from the React frontend (http://localhost:3000) to access the Express API (http://localhost:5000).
- Security Considerations: Be cautious when enabling cors() for production applications. Always restrict allowed origins.
Step 2: Set Up a .env File to Store API Key Securely
- In WebStorm’s Project Explorer,in main directory or create a special directory if desired
- Click New > File and name it .env.
- Add the following line to the .env file:
GEMINI_API_KEY=your_actual_api_key_here
Replace your_actual_api_key_here with your actual Gemini API key.
Step 3: Create an API Route in Express
- Open server.js or index.js in the backend folder.
- Modify it to include the Gemini API route:
# modified index.js or (similar file)
require("dotenv").config(); const express = require("express"); const cors = require("cors"); const { GoogleGenerativeAI } = require("@google/generative-ai"); const app = express(); const port = 5000; const apiKey = process.env.GEMINI_API_KEY; app.use(cors()); app.use(express.json()); const genAI = new GoogleGenerativeAI(apiKey); app.post("/generate", async (req, res) => { try { const { prompt } = req.body; const model = genAI.getGenerativeModel({ model: "gemini-pro" }); const result = await model.generateContent(prompt); res.json({ response: result.response.text() }); } catch (error) { res.status(500).json({ error: error.message }); } }); app.listen(port, () => { console.log(`Server running on http://localhost:${port}`); });
- Run the backend server: (or deploy to a cloud service as desired)
- In WebStorm, go to Run > Run 'index.js'.
- The server should start at http://localhost:5000.
Step 4: Create a React Frontend to Use the Gemini API
- In WebStorm’s Terminal, navigate to the project’s root folder and create a React app:
npx create-react-app frontend
OR npm install -g create-react-app - Once created, navigate into the frontend folder:
cd frontend
- Install Axios to make API calls from React
npm install axios
- Open src/App.js and modify/replace its contents with something like the following (this is just an example) NOTICE how it uses the NodeJS service (at port 5000) to post a request & it is the backend NodeJS service that has the Gemini API key:
import React, { useState } from "react"; import axios from "axios"; function App() { const [prompt, setPrompt] = useState(""); const [response, setResponse] = useState(""); const handleGenerate = async () => { try { const res = await axios.post("http://localhost:5000/generate", { prompt }); setResponse(res.data.response); } catch (error) { console.error("Error:", error); } }; return ( <div> <h1>Gemini AI Chat</h1> <textarea placeholder="Enter a prompt..." value={prompt} onChange={(e) => setPrompt(e.target.value)} /> <button onClick={handleGenerate}>Generate</button> <p>{response}</p> </div> ); } export default App;
- Start the React frontend:
- In WebStorm’s terminal, navigate to the frontend folder:
cd frontend
- Run the React app:
npm start
- The frontend should open in the browser at http://localhost:3000.
- In WebStorm’s terminal, navigate to the frontend folder:
7. Monitor Usage
Regularly monitor the usage of the Gemini API to ensure it stays within the limits of the educational credits. This can be done through the Google Cloud Console.