Titan Planet Logo

Example Actions

Real-world examples of Titan actions for authentication, database integration, and more.

Build powerful backends with these practical examples. Titan makes it easy to combine speed and simplicity.

Authentication & Database Flow

This example demonstrates a complete authentication system: routing, database connection pooling, SQL-based login, and JWT session verification.

app/app.js
import t from "@titan/route";

// Define routes and map them to actions
t.post("/lg").action("login") // Payload: { "username": "titan", "password": "..." }
t.post("/me").action("me")     // Payload: { "tk": "..." }

t.start(5100, "Titan Running!");
app/db/db.js
export const db = () => {
    // Connect with a connection pool (max 10 connections)
    return t.db.connect(process.env.DB_URI, {
        max: 10
    })
}
app/actions/login.js
/* eslint-disable titanpl/drift-only-titan-async */
import "@titanpl/node/globals";
import { fs, response } from "@titan/native";
import { db } from "db/db";

export const login = (req) => {
    // Read external SQL file
    const sql = fs.readFile("../app/db/login.sql");
    const { username, password } = req.body;

    if (!username || !password) {
        return response.json(
            { error: "Username and password required" },
            { status: 400 }
        );
    }

    const conn = db();

    // Execute query inside drift()
    const rows = drift(
        conn.query(sql, [username])
    );

    if (!rows || rows.length === 0) {
        return response.json(
            { error: "Invalid credentials" },
            { status: 401 }
        );
    }

    const user = rows[0];

    // Verify password using Rust-native crypto
    const valid = t.password.verify(password, user.password);

    if (!valid) {
        return response.json(
            { error: "Invalid credentials" },
            { status: 401 }
        );
    }

    delete user.password;

    // Sign JWT for session management
    const token = t.jwt.sign(
        {
            id: user.id,
            username: user.username,
            email: user.email
        },
        process.env.JWT_SECRET, // Protected secret
        { expiresIn: "1m" }
    );

    return response.json({
        success: true,
        token,
        user
    });
};
app/actions/me.js
import { jwt } from "@titan/native"

export const me = (req) => {
    const { tk } = req.body;

    // Verify token and return user identity
    const user = jwt.verify(tk, process.env.JWT_SECRET);

    return user;
}
app/db/login.sql
SELECT id, username, email, password
FROM users
WHERE username = $1
LIMIT 1;

External Integration

Connect to third-party services like Supabase using standard REST APIs with Rust-native performance.

Setup

Ensure you have SUPABASE_ANON_KEY and SUPABASE_PROJECT_ID in your .env file.

app/actions/register_external.js
export default function register(req) {
  const { email, password } = req.body;

  if (!email || !password) {
    return { status: 400, error: "Email and password are required" };
  }

  const password_hash = t.password.hash(password);

  const res = drift(t.fetch(
    `https://${process.env.SUPABASE_PROJECT_ID}.supabase.co/rest/v1/users`,
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "apikey": process.env.SUPABASE_ANON_KEY,
        "Authorization": `Bearer ${process.env.SUPABASE_ANON_KEY}`,
        "Prefer": "return=representation"
      },
      body: { email, password_hash }
    }
  ));

  if (res.status === 409) {
    return { status: 409, error: "Email already registered" };
  }

  if (res.status < 200 || res.status >= 300) {
    return { status: res.status, error: res.body || "Creation failed" };
  }

  return {
    status: 201,
    message: "User registered successfully",
  };
}

Database Operations

Interacting with PostgreSQL using the native t.db connector.

app/actions/list_users.js
export default function(req) {
    const db = t.db.connect(process.env.DATABASE_URL);
    
    // Read SQL from external file for clean code
    const sql = t.read("../db/get_users.sql");
    
    const users = drift(db.query(sql, [req.query.active || true]));
    
    return {
        status: 200,
        json: users
    };
}

What's Next?

Check out the Runtime APIs to see exactly what the t object can do.

On this page