cd..blog

Full-Stack AI: Sails.js, Together AI, & Heroku with TypeScript

const published = "Jan 22, 2026, 10:37 PM";const readTime = 5 min;
sailsjsherokutogether-aitypescriptai-api
Build a robust AI-powered backend using Sails.js, integrate Together AI for advanced capabilities, and deploy seamlessly to Heroku, all with TypeScript.

Full-Stack AI: Sails.js, Together AI, & Heroku with TypeScript

In the rapidly evolving landscape of web development, integrating AI capabilities into robust backend systems and deploying them efficiently is paramount. This guide demonstrates how to combine the power of Sails.js, the intelligence of Together AI, and the seamless deployment capabilities of Heroku, all while leveraging TypeScript for enhanced developer experience and code quality.

1. Setting Up Your Sails.js Backend with TypeScript

Sails.js provides a convention-over-configuration MVC framework for Node.js, ideal for building scalable APIs. We'll use TypeScript to ensure type safety and maintainability from the start.

First, install the Sails CLI and create a new project with TypeScript support:

npm install -g sails@latest
sails new ai-backend --no-frontend --template=typescript
cd ai-backend

Sails.js (official documentation). It simplifies API development with its ORM (Waterline) and robust routing. TypeScript (official documentation) adds static typing, reducing runtime errors and improving code readability.

2. Package Management and Together AI Integration

Efficient package management is crucial. We'll use npm to install the Together AI SDK and other necessary dependencies. Together AI offers powerful large language models (LLMs) via a simple API.

Install the Together AI SDK and any type definitions:

npm install together-ai @types/node

Together AI (official documentation) provides access to state-of-the-art generative AI models. npm (official documentation) is the default package manager for Node.js, handling project dependencies reliably.

Next, create a Sails service to encapsulate Together AI interactions. Generate the service:

sails generate service together-ai

Edit api/services/TogetherAiService.ts:

// api/services/TogetherAiService.ts
import Together from "together-ai";

declare var sails: any;

export default class TogetherAiService {
  private together: Together;

  constructor() {
    const apiKey = process.env.TOGETHER_API_KEY;
    if (!apiKey) {
      sails.log.error("TOGETHER_API_KEY environment variable is not set.");
      throw new Error("TOGETHER_API_KEY is required.");
    }
    this.together = new Together({ apiKey });
  }

  /**
   * Generates text using a Together AI model.
   * @param prompt The input prompt for the model.
   * @param model The model to use (e.g., "mistralai/Mixtral-8x7B-Instruct-v0.1").
   * @returns The generated text.
   */
  public async generateText(prompt: string, model: string = "mistralai/Mixtral-8x7B-Instruct-v0.1"): Promise<string | undefined> {
    try {
      const response = await this.together.chat.completions.create({
        model: model,
        messages: [{ role: "user", content: prompt }],
      });
      return response.choices[0]?.message?.content;
    } catch (error) {
      sails.log.error("Error generating text with Together AI:", error);
      throw error;
    }
  }
}

Now, create a controller to expose this functionality via an API endpoint. Generate the controller:

sails generate controller ai

Edit api/controllers/AiController.ts:

// api/controllers/AiController.ts
import { Request, Response } from "express";

declare var sails: any;

export default class AiController {
  public async generate(req: Request, res: Response): Promise<Response> {
    const { prompt, model } = req.body;

    if (!prompt) {
      return res.badRequest({ message: "'prompt' is required." });
    }

    try {
      const generatedText = await sails.services.togetheraiservice.generateText(prompt, model);
      return res.ok({ generatedText });
    } catch (error) {
      sails.log.error("Failed to generate AI text:", error);
      return res.serverError({ message: "Failed to generate AI text." });
    }
  }
}

Finally, add a route in config/routes.ts:

// config/routes.ts
export const routes = {
  "POST /ai/generate": "AiController.generate",
};

3. Deployment to Heroku

Heroku provides a powerful platform-as-a-service (PaaS) for deploying Node.js applications with minimal configuration. We'll prepare our Sails.js app for Heroku deployment.

Heroku (official documentation) simplifies cloud application deployment, scaling, and management.

Create a Procfile at the root of your project to tell Heroku how to run your application:

// Procfile
web: node app.js

Ensure your package.json includes a start script, which sails new typically sets up for you:

// package.json (excerpt)
{
  "name": "ai-backend",
  "private": true,
  "version": "0.0.0",
  "description": "",
  "scripts": {
    "start": "node app.js",
    "test": "npm run lint && npm run custom-tests && echo 'Done.'",
    "lint": "eslint . --max-warnings=0 --report-unused-disable-directives && echo '✔  Lint complete.'"
  },
  "main": "app.js",
  "dependencies": {
    "together-ai": "^0.2.1",
    "sails": "^1.5.0",
    "grunt": "3.0.0",
    "sails-hook-grunt": "^2.0.0",
    "sails-hook-orm": "^3.0.0",
    "sails-hook-sockets": "^2.0.0"
  },
  "devDependencies": {
    "@types/node": "^20.0.0",
    "eslint": "^8.0.0",
    "typescript": "^5.0.0"
  }
}

Initialize a Git repository and commit your code:

git init
git add .
git commit -m "Initial commit with Sails.js and Together AI integration"

Create a Heroku app and push your code:

heroku create your-ai-app-name
git push heroku master

Finally, set your Together AI API key as an environment variable on Heroku:

heroku config:set TOGETHER_API_KEY="YOUR_TOGETHER_AI_API_KEY"

4. Best Practices & Actionable Insights

  • Environment Variables: Always use process.env for sensitive data like API keys. Never hardcode them. Heroku's config:set makes this straightforward.
  • Error Handling: Implement robust try...catch blocks in your services and controllers to gracefully handle API errors and provide meaningful responses.
  • TypeScript Benefits: Leverage TypeScript's type checking for service inputs/outputs and controller request bodies to catch errors early in development.
  • Structured Logging: Utilize Sails' built-in logger (sails.log) for consistent and debuggable output, especially useful in production environments like Heroku.

This integrated stack provides a powerful, scalable, and maintainable foundation for building intelligent web applications. You now have a Sails.js backend, powered by Together AI, and deployed effortlessly on Heroku, ready to serve advanced AI capabilities.