Skip to content

Node.js Integration

Complete Node.js examples for Lunar Stream API integration.

Installation

bash
npm install axios dotenv

API Client

javascript
// lunar-stream-client.js
const axios = require('axios');

class LunarStreamClient {
  constructor(apiKey, projectId) {
    this.projectId = projectId;
    this.client = axios.create({
      baseURL: process.env.LUNAR_STREAM_API_URL || 'https://api.lunarstream.kozow.com/api/v1',
      headers: {
        'ls-api-key': apiKey,
        'Content-Type': 'application/json'
      }
    });
  }

  async getMediaServers() {
    const response = await this.client.get('/media-servers/available', {
      params: { projectId: this.projectId }
    });
    return response.data.data;
  }

  async createLivestream(name, mediaServerId) {
    const response = await this.client.post('/livestream', {
      name,
      projectId: this.projectId,
      mediaServerId
    });
    return response.data.data;
  }

  async getLivestream(id) {
    const response = await this.client.get(`/livestream/${id}`, {
      params: { projectId: this.projectId }
    });
    return response.data.data;
  }

  async listLivestreams(page = 1, limit = 10) {
    const response = await this.client.get('/livestream', {
      params: { projectId: this.projectId, page, limit }
    });
    return response.data;
  }

  async deleteLivestream(id) {
    const response = await this.client.delete(`/livestream/${id}`, {
      params: { projectId: this.projectId }
    });
    return response.data;
  }

  async generatePushToken(streamKey, expiresIn = 3600) {
    const response = await this.client.post('/livestream/generate-push-token', {
      projectId: this.projectId,
      streamKey,
      expiresIn
    });
    return response.data.data;
  }

  async getStreamInfo(streamKey) {
    const response = await this.client.get(`/livestreams/stream-info/${streamKey}`);
    return response.data.data;
  }
}

module.exports = LunarStreamClient;

Express.js Example

javascript
// server.js
require('dotenv').config();
const express = require('express');
const LunarStreamClient = require('./lunar-stream-client');

const app = express();
app.use(express.json());

const lunarStream = new LunarStreamClient(
  process.env.LUNAR_STREAM_API_KEY,
  process.env.LUNAR_STREAM_PROJECT_ID
);

// Create a new livestream
app.post('/api/streams', async (req, res) => {
  try {
    const { name } = req.body;

    const servers = await lunarStream.getMediaServers();
    if (servers.length === 0) {
      return res.status(503).json({ error: 'No media servers available' });
    }

    const stream = await lunarStream.createLivestream(name, servers[0].id);

    res.json({
      id: stream.id,
      name: stream.name,
      rtmpUrl: `${stream.rmtpServer}/${stream.streamKeyWithParams}`,
      hlsUrl: stream.hlsSources?.[0]?.url,
      status: stream.status
    });
  } catch (error) {
    console.error('Create stream error:', error.response?.data || error.message);
    res.status(500).json({ error: 'Failed to create stream' });
  }
});

// Get stream info for viewers (public)
app.get('/api/streams/:streamKey', async (req, res) => {
  try {
    const { streamKey } = req.params;
    const stream = await lunarStream.getStreamInfo(streamKey);

    res.json({
      name: stream.name,
      status: stream.status,
      hlsUrls: stream.hlsSources
    });
  } catch (error) {
    res.status(404).json({ error: 'Stream not found' });
  }
});

// Refresh push token
app.post('/api/streams/:streamKey/refresh-token', async (req, res) => {
  try {
    const { streamKey } = req.params;
    const { expiresIn = 7200 } = req.body;
    const tokenData = await lunarStream.generatePushToken(streamKey, expiresIn);

    res.json({
      rtmpUrl: tokenData.rtmpUrl,
      streamKeyWithToken: tokenData.streamKeyWithToken,
      expiresAt: tokenData.expiresAt
    });
  } catch (error) {
    res.status(500).json({ error: 'Failed to refresh token' });
  }
});

// List all livestreams
app.get('/api/streams', async (req, res) => {
  try {
    const { page = 1, limit = 10 } = req.query;
    const result = await lunarStream.listLivestreams(Number(page), Number(limit));

    res.json({
      streams: result.data,
      pagination: result.meta?.pagination
    });
  } catch (error) {
    res.status(500).json({ error: 'Failed to list streams' });
  }
});

// Delete livestream
app.delete('/api/streams/:id', async (req, res) => {
  try {
    const { id } = req.params;
    await lunarStream.deleteLivestream(id);
    res.json({ success: true });
  } catch (error) {
    res.status(500).json({ error: 'Failed to delete stream' });
  }
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

Environment Variables

bash
# .env
LUNAR_STREAM_API_URL=https://api.lunarstream.kozow.com/api/v1
LUNAR_STREAM_API_KEY=ls_proj_v1_your_api_key_here
LUNAR_STREAM_PROJECT_ID=your-project-id-here
PORT=3000

Usage Examples

bash
# Create a stream
curl -X POST http://localhost:3000/api/streams \
  -H "Content-Type: application/json" \
  -d '{"name": "My Stream"}'

# Get stream info
curl http://localhost:3000/api/streams/ee04affe2a669854052102fe762bd715

# List streams
curl "http://localhost:3000/api/streams?page=1&limit=10"

# Refresh token
curl -X POST http://localhost:3000/api/streams/ee04affe2a669854052102fe762bd715/refresh-token \
  -H "Content-Type: application/json" \
  -d '{"expiresIn": 7200}'

Released under the MIT License.