JAVASCRIPT TUTORIAL
Astrology API JavaScript Guide
Complete JavaScript tutorial for astrology API. Build horoscope apps with React, Node.js, Next.js with TypeScript support.
January 7, 2026
-
18 min read
Installation
# NPM
npm install @vedika-io/sdk
# Yarn
yarn add @vedika-io/sdk
# PNPM
pnpm add @vedika-io/sdk
Quick Start
import { VedikaClient } from '@vedika-io/sdk';
const vedika = new VedikaClient({ apiKey: 'YOUR_API_KEY' });
// Generate birth chart
const chart = await vedika.getBirthChartV2('birth-chart', {
datetime: '1990-05-15T14:30:00+05:30',
latitude: 28.6139,
longitude: 77.2090,
timezone: '+05:30'
});
console.log(`Ascendant: ${chart.ascendant.sign}`);
console.log(`Moon Sign: ${chart.moonSign}`);
console.log(`Sun Sign: ${chart.sunSign}`);
// List all planets
chart.planets.forEach(planet => {
console.log(`${planet.name}: ${planet.sign} at ${planet.degree}°`);
});
TypeScript Support
import { VedikaClient } from '@vedika-io/sdk';
interface BirthDetails {
datetime: string;
latitude: number;
longitude: number;
timezone?: string;
ayanamsa?: 'lahiri' | 'raman' | 'krishnamurti';
}
interface ChartPlanet {
name: string;
sign: string;
house: number;
degree: number;
isRetrograde: boolean;
}
const vedika = new VedikaClient({ apiKey: process.env.VEDIKA_API_KEY! });
async function analyzeBirthChart(details: BirthDetails): Promise<{
sunSign: string;
moonSign: string;
ascendant: string;
planets: ChartPlanet[];
}> {
const chart = await vedika.getBirthChartV2('birth-chart', details);
return {
sunSign: chart.sunSign,
moonSign: chart.moonSign,
ascendant: chart.ascendant.sign,
planets: chart.planets
};
}
// Usage with full type safety
const analysis = await analyzeBirthChart({
datetime: '1990-05-15T14:30:00+05:30',
latitude: 28.6139,
longitude: 77.2090,
timezone: '+05:30',
ayanamsa: 'lahiri'
});
React Hooks
import { useEffect, useState } from 'react';
import { VedikaProvider, useVedikaClient, useHoroscope } from '@vedika-io/react';
// Wrap your app once: <VedikaProvider apiKey={apiKey}><HoroscopeApp /></VedikaProvider>
function HoroscopeApp() {
const client = useVedikaClient();
const [chart, setChart] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
client.getBirthChartV2('birth-chart', {
datetime: '1990-05-15T14:30:00+05:30',
latitude: 28.6139,
longitude: 77.2090,
timezone: '+05:30'
}).then(setChart).catch(setError);
}, [client]);
if (error) return <div>Error: {error.message}</div>;
if (!chart) return <div>Loading chart...</div>;
return (
<div className="birth-chart">
<h2>Your Birth Chart</h2>
<p>Ascendant: {chart.ascendant.sign}</p>
<p>Moon Sign: {chart.moonSign}</p>
<p>Sun Sign: {chart.sunSign}</p>
<h3>Planets</h3>
<ul>
{chart.planets.map(planet => (
<li key={planet.name}>
{planet.name}: {planet.sign} ({planet.degree.toFixed(2)}°)
{planet.isRetrograde && ' (R)'}
</li>
))}
</ul>
</div>
);
}
// Daily horoscope hook
function DailyHoroscope({ sign }) {
const { data: horoscope, loading, fetch } = useHoroscope();
useEffect(() => {
fetch(sign.toLowerCase(), { period: 'daily' });
}, [sign]);
if (loading || !horoscope) return <div>Loading...</div>;
return (
<div className="horoscope">
<h2>{sign} Daily Horoscope</h2>
<p>{horoscope.prediction}</p>
<p>Lucky Number: {horoscope.luckyNumber}</p>
<p>Lucky Color: {horoscope.luckyColor}</p>
</div>
);
}
Next.js Integration
// app/api/horoscope/route.ts
import { VedikaClient } from '@vedika-io/sdk';
import { NextRequest, NextResponse } from 'next/server';
const vedika = new VedikaClient({ apiKey: process.env.VEDIKA_API_KEY! });
export async function POST(request: NextRequest) {
const { datetime, latitude, longitude, timezone } = await request.json();
try {
const chart = await vedika.getBirthChartV2('birth-chart', {
datetime,
latitude,
longitude,
timezone
});
return NextResponse.json({
ascendant: chart.ascendant,
planets: chart.planets,
houses: chart.houses,
moonSign: chart.moonSign,
sunSign: chart.sunSign
});
} catch (error) {
return NextResponse.json(
{ error: 'Failed to generate chart' },
{ status: 500 }
);
}
}
// app/horoscope/page.tsx
'use client';
import { useState } from 'react';
export default function HoroscopePage() {
const [chart, setChart] = useState(null);
const [loading, setLoading] = useState(false);
async function generateChart(e: React.FormEvent) {
e.preventDefault();
setLoading(true);
const formData = new FormData(e.target as HTMLFormElement);
const response = await fetch('/api/horoscope', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
datetime: formData.get('datetime'),
latitude: parseFloat(formData.get('latitude') as string),
longitude: parseFloat(formData.get('longitude') as string),
timezone: '+05:30'
})
});
setChart(await response.json());
setLoading(false);
}
return (
<form onSubmit={generateChart}>
<input name="datetime" type="datetime-local" required />
<input name="latitude" type="number" step="0.0001" required />
<input name="longitude" type="number" step="0.0001" required />
<button type="submit" disabled={loading}>
{loading ? 'Generating...' : 'Generate Chart'}
</button>
{chart && <ChartDisplay chart={chart} />}
</form>
);
}
Node.js Backend
import express from 'express';
import { VedikaClient } from '@vedika-io/sdk';
const app = express();
const vedika = new VedikaClient({ apiKey: process.env.VEDIKA_API_KEY });
// askQuestionStream yields the data of each server-sent event as a JSON string.
// "clause" events carry the next piece of the answer in `text`; a "completed"
// event carries the whole answer in `response`.
async function* answerText(stream) {
let sawText = false;
for await (const chunk of stream) {
let event;
try { event = JSON.parse(chunk); } catch { continue; }
if (event.text) { sawText = true; yield event.text; }
else if (event.response && !sawText) yield event.response;
}
}
app.use(express.json());
// Birth chart endpoint
app.post('/api/birth-chart', async (req, res) => {
const { datetime, latitude, longitude, timezone, ayanamsa } = req.body;
try {
const chart = await vedika.getBirthChartV2('birth-chart', {
datetime,
latitude,
longitude,
timezone,
ayanamsa: ayanamsa || 'lahiri'
});
res.json(chart);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Kundli matching endpoint
app.post('/api/match', async (req, res) => {
const { male, female } = req.body;
try {
const match = await vedika.getGunaMilan(male, female);
res.json({
score: match.total_points,
maxScore: match.maximum_points,
percentage: match.percentage,
recommendation: match.recommendation,
kootas: match.guna_kootas
});
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// AI chat endpoint with streaming
app.post('/api/chat', async (req, res) => {
const { question, birthDetails } = req.body;
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
const stream = vedika.askQuestionStream({
question,
birthDetails
});
for await (const text of answerText(stream)) {
res.write(`data: ${JSON.stringify({ text })}\n\n`);
}
res.write('data: [DONE]\n\n');
res.end();
});
app.listen(3000, () => console.log('Server running on port 3000'));
AI Chat with Streaming
import { VedikaClient } from '@vedika-io/sdk';
const vedika = new VedikaClient({ apiKey: 'YOUR_API_KEY' });
// Non-streaming
const response = await vedika.askQuestion({
question: 'What career paths suit me based on my chart?',
birthDetails: {
datetime: '1990-05-15T14:30:00+05:30',
latitude: 28.6139,
longitude: 77.2090
}
});
console.log(response.response);
// Streaming (for real-time UI updates)
// askQuestionStream yields the data of each server-sent event as a JSON string.
// "clause" events carry the next piece of the answer in `text`; a "completed"
// event carries the whole answer in `response`.
async function* answerText(stream) {
let sawText = false;
for await (const chunk of stream) {
let event;
try { event = JSON.parse(chunk); } catch { continue; }
if (event.text) { sawText = true; yield event.text; }
else if (event.response && !sawText) yield event.response;
}
}
const stream = vedika.askQuestionStream({
question: 'Explain my upcoming Saturn dasha in detail',
birthDetails: {
datetime: '1990-05-15T14:30:00+05:30',
latitude: 28.6139,
longitude: 77.2090
}
});
for await (const text of answerText(stream)) {
process.stdout.write(text); // Real-time output
}
// React component with streaming
function AstrologyChat() {
const [messages, setMessages] = useState([]);
const [streaming, setStreaming] = useState(false);
async function askQuestion(question: string) {
setStreaming(true);
setMessages(prev => [...prev, { role: 'assistant', content: '' }]);
const stream = vedika.askQuestionStream({
question,
birthDetails: userBirthDetails
});
let fullResponse = '';
for await (const text of answerText(stream)) {
fullResponse += text;
setMessages(prev => {
const updated = [...prev];
updated[updated.length - 1].content = fullResponse;
return updated;
});
}
setStreaming(false);
}
return (
<div className="chat">
{messages.map((msg, i) => (
<div key={i} className={`message ${msg.role}`}>
{msg.content}
</div>
))}
<input
type="text"
onKeyDown={e => e.key === 'Enter' && askQuestion(e.target.value)}
disabled={streaming}
/>
</div>
);
}
Start Building with JavaScript
The Vedika JavaScript SDK works in browsers, Node.js, and edge runtimes. Full TypeScript support with React hooks included.