Skip to main content

Unleashing Gemini API Features In Your Next.js App With API Routes (With Code & Github Repo Link)

 The emergence of large language models (LLMs) like Gemini has revolutionized how we interact with technology. Their ability to generate human-like text, translate languages, write different kinds of creative content, and answer your questions in an informative way opens up a world of possibilities for web applications.


In this blog post, we'll guide you through integrating Gemini AI into your Next.js project using API routes.

Clone project from Github: Gemini API using Next.js API routes - github project link


Setting the Stage: Project Setup and API Keys

Before we dive into coding, let's ensure our Next.js project is ready for action. NextJs Page Router will be used in the blogpost.


New Project: If you don't have a Next.js project, create one using the following command:


npx create-next-app my-gemini-app 

You will prompted to answer some questions about the nextjs project.

Need to install the following packages:
create-next-app@14.2.5
Ok to proceed? (y) y
Would you like to use TypeScript? No / Yes
Would you like to use ESLint? No / Yes
Would you like to use Tailwind CSS? No / Yes
Would you like to use `src/` directory? No / Yes
Would you like to use App Router? (recommended) No / Yes
Would you like to customize the default import alias (@/*)? No / Yes

After successful installation:


cd my-gemini-app


Gemini API Key: To access Gemini, you need an API key. https://ai.google.dev/gemini-api You can get one by signing up & setting up account . Once you have your API key, store it securely in your project's environment variables. We'll cover this later.


Clone project from Github: Gemini API using Next.js API routes - github project link


Building the Backend: API Routes for Gemini Power

Next.js API routes are the perfect mechanism to interact with Gemini API from your frontend. Here's how we'll construct our API route:


1. Create the API Route: 

Create a file named [...nextroute].js (or any name you prefer) inside the pages/api directory of your project. This file will house our API route handler.


2. Install the @google/generative-ai Package:

 * See the getting started guide for more information https://ai.google.dev/gemini-api/docs/get-started/node


npm install @google/generative-ai


3. Import the Necessary Modules:


import { GoogleGenerativeAI } from "@google/generative-ai";


4. Configure GoogleGenerativeAI:


const apiKey = process.env.GEMINI_API_KEY

Replace process.env.GEMINI_API_KEY with the environment variable containing your API key. To set this up, create a .env.local file at the root of your project and add the line GEMINI_API_KEY=your_api_key. Remember to never commit your API key to version control!


5. Handle Requests:


import { GoogleGenerativeAI } from "@google/generative-ai"; // Next.js API route support: https://nextjs.org/docs/api-routes/introduction /** * api key from env */ const apiKey = process.env.GEMINI_API_KEY; export default async function handler(req, res) { if (req.method === "POST") { const { prompt } = req.body; if (prompt === "") { return res.status(400).json({ error: "fill all fields" }); } try { const genAI = new GoogleGenerativeAI(apiKey); const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash", systemInstruction: { parts: [ { text: `You are a helpful assistant. Please be concise and precise. **Your response must always be a valid JSON object with the following structure: * **text_content:** the generated content. `, }, ], role: "model", }, }); const parts = [{ text: prompt }]; /** * generation config for gemini api calls * setting responseMimeType to JSON to get back response in json format */ const generationConfig = { temperature: 1, topP: 0.95, topK: 64, maxOutputTokens: 8192, responseMimeType: "application/json", }; const result = await model.generateContent({ contents: [{ role: "user", parts }], generationConfig, }); let response = ""; if ( result.response.promptFeedback && result.response.promptFeedback.blockReason ) { response = { error: `Blocked for ${result.response.promptFeedback.blockReason}`, }; return res.status(200).json(response); } response = result.response.candidates[0].content.parts[0].text; return res.status(200).json(response); } catch (error) { console.error(error); return res .status(500) .json({ error: "Failed to get a response from Gemini" }); } } else { return res.status(405).json({ message: "Method not allowed" }); } }

This code handles POST requests. It extracts the user's prompt from the request body, interacts with the Gemini API, and sends back the response.


Crafting the Frontend: Input, Submit, and Output

Now, let's build the frontend component to interact with our API route:


1. Create the Component: 

Inside your components directory (or any suitable location), create a file named GeminiPrompt.js.


2. Structure the Component:


import React, { useState } from "react"; const GeminiPrompt = () => { const [prompt, setPrompt] = useState(""); const [response, setResponse] = useState(""); const handleSubmit = async (event) => { event.preventDefault(); try { const res = await fetch("/api/gemini", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ prompt }), }); const data = await JSON.parse(await res.json()); console.log(data, "data response"); console.log(data?.text_content, "text_content"); setResponse(data?.text_content); } catch (error) { console.error(error); setResponse("An error occurred. Please try again later."); } }; return ( <div> <h2>Ask Gemini anything!</h2> <form onSubmit={handleSubmit}> <input type="text" placeholder="Enter your prompt here" value={prompt} onChange={(e) => setPrompt(e.target.value)} /> <button type="submit">Submit</button> </form> <div> <h3>Response:</h3> <p>{response}</p> </div> </div> ); }; export default GeminiPrompt;

This component manages the input, submission, and display of results.


3. Integrate into Your Page:

 Import and use the GeminiPrompt component in the relevant page of your Next.js app:


import GeminiPrompt from '../components/GeminiPrompt';


function HomePage() {

  return (

    <div>

      <GeminiPrompt />

    </div>

  );

}


export default HomePage;


Putting it All Together: Running Your Application


Now, start your Next.js development server:


npm run dev

Visit http://localhost:3000 in your browser, and you should see your Gemini AI-powered app!

gemini api with nextjs api routes

gemini api with nextjs api routes - after api call

File / folder structure:


my-gemini-app/

├── public/

│   └── favicon.ico

├── pages/

│   ├── api/

│   │   └── [...nextroute].js  

│   └── index.js  

├── components/

│   └── GeminiPrompt.js

├── styles/

│   └── globals.css

├── next.config.js

├── .env.local  

└── package.json 


Explanation:

public/:

Contains static assets like images, favicon, etc.

favicon.ico: The default favicon for your application.


pages/:

Holds your Next.js page components.


index.js: This is the main entry point for your Next.js app. It's likely where you'll import and display your GeminiPrompt component.


api/:

Houses your API routes for server-side logic.

[...nextroute].js: This file defines your API route to interact with Gemini (see the code in the previous response).


components/:

Contains reusable components for your application's UI.

GeminiPrompt.js: The component that handles user input, submits it to the API, and displays the response.


styles/:

Stores your CSS files.

globals.css: A common file for global styles.


next.config.js:

The Next.js configuration file where you can customize various aspects of your app's behavior.


.env.local:

Stores environment variables that you don't want to commit to version control (like your Gemini API key).


package.json:

Defines your project's dependencies, scripts, and other metadata.


Key Points:

  • [...nextroute].js: The use of [...] in the filename makes this an API route that can handle any incoming request. This is a convention for defining API routes in Next.js.
  • index.js: You might want to create additional pages within the pages/ directory as your app grows.
  • components/: Organizing your UI components into a components folder promotes code reusability and maintainability.
  • .env.local: Remember to never commit your API key to version control. Store it safely in this file and use it in your code by accessing it via process.env.GEMINI_API_KEY.

This file structure is a starting point, and you can customize it further to meet the specific needs of your project.



Conclusion

By seamlessly integrating Gemini AI through API routes, you can elevate your Next.js applications to a new level of intelligence and interactivity. The possibilities are endless: from creating conversational chatbots to generating personalized content and much more. This post provides a solid foundation, and you can further customize it by exploring advanced features offered by Gemini API, tailoring it to your specific needs and creative vision.

Clone project from Github: Gemini API using Next.js API routes - github project link

Note:You can also access Gemini using GCP Vertex AI ( not covered here)

Comments

Topics

Show more