Effortless AI Integration in Next.js with Ikomia SCALE

Allan Kouidri
-
2/12/2025
Next.js AI illustration

Adding AI to your Next.js app has never been simpler! In this guide, we'll walk you through deploying and integrating powerful AI models, no Python required. With just a few clicks, you can access state-of-the-art (SOTA) algorithms from the Ikomia HUB and bring AI features into your JavaScript app hassle-free.

Here's what you'll learn:

  • Quickly deploy top-tier AI models from the Ikomia HUB, like Computer Vision and Image Generation tools.
    • No coding needed.
    • Pick your infrastructure (CPU, GPU), provider, region, and instance size.
  • Use an easy-to-handle client library to integrate Ikomia SCALE deployments into your JavaScript app.
    • Securely handle authentication with the Ikomia SCALE API.
    • Work with a simple interface to set up and run deployments.
    • Easily manage and process results.

Step 1: Deploy your algorithm

Prerequisite

Before getting started, make sure you have an Ikomia account. If you don’t have one yet, you can sign up using your email, Google, or GitHub account.

1. Select your algorithm

The Ikomia HUB provides access to over 100 AI algorithms, all deployable in just a few clicks. For this guide, we’ll be using the FLUX.1 diffusion model, a cutting-edge algorithm for image generation.

Simply navigate to the Ikomia HUB, search for FLUX.1, and select it for deployment.

Ikomia HUB Deploy algorithm

2. Create your deployment

Ikomia SCALE lets you deploy your workflows across various cloud providers and regions. You can choose from three main compute infrastructures:

  • Serverless: CPU-only, pay only for execution time.
  • CPU Instances: Dedicated CPU-only instances, billed per second while in use.
  • GPU Instances: Dedicated GPU-accelerated instances, billed per second while in use.

For FLUX.1, we recommend at least 24GB of VRAM. In this example, we'll select the Nvidia L4 size M from Google Cloud for optimal performance.To deploy your selected workflow, follow these steps:

  1. On the right side of the page, find the deployment interface.
  2. Choose your cloud provider, deployment type, region, and instance size.

Click Add Deployment to launch your workflow.

Deployement scale

Once added, your deployment will appear in the deployment list on the left side of the page. Setup time will vary based on the workflow and chosen configuration.

3. Test your deployment

The SCALE platform offers an intuitive Test Interface to quickly verify your deployed workflow.

Open the Test Interface

  • Navigate to your workflow page.
  • Click the Test Me button on your deployment or access the endpoint's URL directly.
Ikomia Scale go to test interface button

Run Your Workflow

  • You can trigger the execution by clicking the Run Workflow button or pressing Shift + Enter.

Note: The first run of FLUX.1 takes a few minutes as the system sets up the required models

Ikomia SCALE test interface

This allows you to validate your deployment effortlessly before integrating it into your application.

Step 2: Full stack Integration

1. Installation 

Use your preferred package manager to install the client library:


npm install @ikomia/ikclient

2. Set up a new Next.js project

To create a new Next.js project, run the following command:


npx create-next-app@latest

During installation, you’ll be prompted with several configuration options. You can select the default settings or customize them based on your preferences:


What is your project named? my-app
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 your code inside a `src/` directory? No / Yes
Would you like to use App Router? (recommended) No / Yes
Would you like to use Turbopack for `next dev`?  No / Yes
Would you like to customize the import alias (`@/*` by default)? No / Yes
What import alias would you like configured? @/*

Once the project is created, we get a sneak peek at the final tree structure we'll build by the end of the tutorial.

3. Get your endpoint and generate your token

Before making API requests, you'll need to retrieve your deployment's endpoint and generate a secure token for authentication. Follow these steps to obtain the necessary credentials.

Endpoint

The endpoint is available on the left-hand side of the page under the deployments section.

Ikomia SCALE get endpoint

Token Generation from the SCALE Platform

1. Access Token Management: Navigate to the top right corner of the SCALE platform, then go to the settings or account section where you will find API token management.

2. Create New Token: Click on the option to create a new token. Fill in the required details such as the token's name and expiration date.

3. Generate and Save the Token.

4. Copy the Token: Once generated, copy the token. You are now ready to set the token as an environment variable.

Ikomia SCALE get token

Create a .env file in the root of your project

Create a .env file in your project root directory and define the endpoint URL and authentication token. This file stores environment variables required to connect with the Ikomia SCALE API. The endpoint provides access to your deployed model, while the token ensures authenticated requests. Add the following variables to your .env file:


#------#
# .env #
#------#
ENDPOINT_URL = 'https://h1fppebxv8.nl.gke.ikomia.org'
IKOMIA_TOKEN = '************************************************'

4. Implementing the backend endpoint

Implement a Route Handler to call your deployment and stream the results to the browser using toStreamingResponse:


//---------------------------------//
// app/api/generate-image/route.ts //
//---------------------------------//

import {Client} from '@ikomia/ikclient';
import {toStreamingResponse} from '@ikomia/ikclient/proxy/server';


const imageGenerator = new Client({
  url: process.env.ENDPOINT_URL!,
});

export async function GET(request: Request) {
  // Add your own logic here (e.g. authentication, rate limiting, billing, etc.)

  const url = new URL(request.url);
  const prompt = url.searchParams.get('prompt');

  if (!prompt) {
    return new Response('Missing prompt', {status: 400});
  }

  const stream = imageGenerator.runStream({
    parameters: {prompt},
  });

  // Return as a streaming response
  return toStreamingResponse(stream);
}

Since you are responsible for implementing your backend endpoint, you can easily incorporate your own logic to authenticate users, rate limit requests, add billing or any other custom constraints.

5. Implementing the client-side code for image generation

This React component allows users to input a prompt, sends it to the backend API (/api/generate-image), and displays the generated image. It dynamically updates the estimated time (ETA) and handles errors, ensuring a seamless user experience


  //--------------//
  // app/page.tsx //
  //--------------//
  'use client';

  import { ImageIO } from '@ikomia/ikclient/io';
  import { processStreamingResponse } from '@ikomia/ikclient/proxy/browser';
  import { useState } from 'react';
  import { useFormStatus } from 'react-dom';
  import Image from 'next/image';

  export default function Home() {
    const [eta, setEta] = useState<number>();
    const [error, setError] = useState<Error>();
    const [resultImage, setResultImage] = useState<ImageIO>();

    return (
      <div className="max-w-2xl mx-auto p-6 space-y-8">
        <h1 className="text-2xl font-bold">Image Generator</h1>
        <form
          className="space-y-4"
          action={async (formData: FormData) => {
            const prompt = formData.get('prompt');
            if (!prompt) return;
            // Clear previous results
            setError(undefined);
            setResultImage(undefined);

            // Call our backend endpoint and retrieve the results
            try {
              const response = await fetch(
                `/api/generate-image?prompt=${prompt}`
              );
              const results = await processStreamingResponse(response, progress =>
                setEta(progress.eta[1] ?? undefined)
              );
              setResultImage(results.getOutput<ImageIO>(0));
            } catch (err) {
              setError(err as Error);
            }
          }}
        >
          <input
            type="text"
            name="prompt"
            placeholder="Enter a prompt..."
            className="w-full border-2 border-gray-200 rounded-lg px-4 py-3 focus:outline-none focus:border-orange-500 focus:ring-2 focus:ring-orange-200 transition-all text-lg"
          />
          <SubmitButton eta={eta} />
          {error && <p className="text-red-500 font-medium">{error.message}</p>}
        </form>

        {resultImage && (
          // eslint-disable-next-line @next/next/no-img-element
          <img
            src={resultImage.dataUrl}
            alt="Generated image"
            className="w-full aspect-square object-cover rounded-xl shadow-lg hover:shadow-xl transition-all duration-300"
          />
        )}
      </div>
    );
  }

  function SubmitButton({eta}: {eta?: number}) {
    const {pending} = useFormStatus();

    return (
      <button
        type="submit"
        disabled={pending}
        className="w-full px-6 py-3 bg-orange-500 hover:bg-orange-600 text-white rounded-lg font-semibold shadow-md hover:shadow-lg disabled:opacity-70 disabled:cursor-not-allowed transition-all duration-200"
      >
        {pending
          ? `Generating...${eta ? ` (ETA: ${Math.round(eta / 1000)}s)` : ''}`
          : 'Generate'}
      </button>
    );
  }
  

       

6. Start the development server and generate your image with FLUX.1

Once everything is set up, it's time to run your Next.js app and test the AI-powered image generation with the FLUX.1 model. Follow these steps to get your application up and running:

Start the Development Server

Depending on the package manager you used for installation, run the appropriate command to start your Next.js application:


npm run dev

This will start your Next.js development server, usually at http://localhost:3000/

Access the Image Generation Interface

  1. Open your browser and navigate to http://localhost:3000/.
  2. You should see the input field where you can enter a text prompt for the AI model.
  3. Click the Generate button to start the image generation process.
Ikomia SCALE Next.js development server

Et voilà! Your app is successfully generating images.

Conclusion

Adding AI to your Next.js app is now easier than ever with Ikomia HUB and SCALE. This guide walked you through deploying an AI model, setting up a backend endpoint, and creating a simple front-end to generate images, all without needing Python.

With just a few steps, you can integrate powerful AI models into your app while keeping things flexible. You get to choose your deployment setup and even customize the experience to fit your needs. Plus, since it’s all cloud-based, you don’t have to worry about heavy processing on your local machine!

Now that you’ve got everything up and running, you can start exploring more AI models, fine-tune performance, and add even more cool features to your app! 🚀

Arrow
Arrow
No items found.