본문으로 건너뛰기
cccskills
무료GitHub에 공개

api-proxy-endpoint

Build serverless endpoints that relay external API requests for a dashboard while keeping API keys on the server. Includes Vercel examples for input checks, caching, cross-origin access, and consistent JSON responses.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

원문원문 설명 보기

Create serverless API proxy endpoints that hide API keys and provide a unified backend for the dashboard frontend. Designed for Vercel deployment.

연동 도구Vercel
설치 방법 보기

이럴 때 유용합니다

  • Connect a dashboard to external APIs without exposing API keys
  • Create endpoints for stock quotes and news
  • Standardize API responses and error handling
  • Configure local development for API endpoints

포함된 파일(2)

  • SKILL.md4.9 KB
  • .skill_id33 B

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

API Proxy Endpoint Pattern

External APIs often require API keys that must not be exposed in frontend code. Create serverless proxy endpoints that:

  • Hide API keys on the server side
  • Provide a unified /api/* namespace for the frontend
  • Handle CORS, rate limiting, and error wrapping

Endpoint Structure

Each API endpoint is a file in the api/ directory:

api/
├── stocks.ts          # Stock market data proxy
├── news.ts            # News API proxy
├── calendar.ts        # Calendar events proxy
└── _cors.ts           # Shared CORS helper

CORS Helper

// api/_cors.ts
export function corsHeaders() {
  return {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'GET, OPTIONS',
    'Access-Control-Allow-Headers': 'Content-Type',
  };
}

export function handleCors(req: Request): Response | null {
  if (req.method === 'OPTIONS') {
    return new Response(null, { status: 204, headers: corsHeaders() });
  }
  return null;
}

Example: Stock Proxy Endpoint

// api/stocks.ts
import type { VercelRequest, VercelResponse } from '@vercel/node';

export default async function handler(req: VercelRequest, res: VercelResponse) {
  // CORS
  res.setHeader('Access-Control-Allow-Origin', '*');
  if (req.method === 'OPTIONS') return res.status(204).end();

  const symbols = (req.query.symbols as string || '').split(',').filter(Boolean);
  if (symbols.length === 0) {
    return res.status(400).json({ error: 'Missing symbols parameter' });
  }

  const apiKey = process.env.FINNHUB_API_KEY;
  if (!apiKey) {
    return res.status(500).json({ error: 'API key not configured' });
  }

  try {
    const quotes = await Promise.all(
      symbols.map(async (sym) => {
        const resp = await fetch(
          `https://finnhub.io/api/v1/quote?symbol=${sym}&token=${apiKey}`
        );
        if (!resp.ok) throw new Error(`Finnhub ${resp.status}`);
        const data = await resp.json();
        return {
          symbol: sym,
          price: data.c,       // current price
          change: data.dp,     // percent change
          high: data.h,
          low: data.l,
          open: data.o,
          prevClose: data.pc,
        };
      })
    );
    res.setHeader('Cache-Control', 's-maxage=30, stale-while-revalidate=60');
    return res.json({ quotes });
  } catch (err) {
    console.error('Stock API error:', err);
    return res.status(502).json({ error: 'Upstream API failed' });
  }
}

Example: News Proxy Endpoint

// api/news.ts
import type { VercelRequest, VercelResponse } from '@vercel/node';

export default async function handler(req: VercelRequest, res: VercelResponse) {
  res.setHeader('Access-Control-Allow-Origin', '*');
  if (req.method === 'OPTIONS') return res.status(204).end();

  const apiKey = process.env.NEWS_API_KEY;
  if (!apiKey) return res.status(500).json({ error: 'API key not configured' });

  const query = req.query.q as string || '';
  const category = req.query.category as string || 'general';
  const lang = req.query.lang as string || 'en';

  try {
    const url = query
      ? `https://gnews.io/api/v4/search?q=${encodeURIComponent(query)}&lang=${lang}&max=20&token=${apiKey}`
      : `https://gnews.io/api/v4/top-headlines?category=${category}&lang=${lang}&max=20&token=${apiKey}`;

    const resp = await fetch(url);
    if (!resp.ok) throw new Error(`GNews ${resp.status}`);
    const data = await resp.json();

    res.setHeader('Cache-Control', 's-maxage=120, stale-while-revalidate=300');
    return res.json({
      articles: (data.articles || []).map((a: any) => ({
        title: a.title,
        description: a.description,
        url: a.url,
        source: a.source?.name || '',
        publishedAt: a.publishedAt,
        image: a.image,
      })),
    });
  } catch (err) {
    console.error('News API error:', err);
    return res.status(502).json({ error: 'Upstream API failed' });
  }
}

Key Patterns

  1. One file per API domain in the api/ directory
  2. Always set CORS headers — frontend runs on different origin during dev
  3. Environment variables for API keys (process.env.FINNHUB_API_KEY)
  4. Cache-Control headers for edge caching (Vercel CDN)
  5. Error wrapping — return structured JSON errors, never raw upstream errors
  6. Input validation — validate query parameters before calling upstream
  7. Typed responses — keep response shapes consistent for frontend consumption

Local Development

During vite dev, configure a proxy in vite.config.ts:

export default defineConfig({
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        changeOrigin: true,
      },
    },
  },
});

Or use vercel dev to run serverless functions locally.

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

Prepare audio stems, the separate parts of a track, for mixing by matching their durations with silence, loops, or crossfades. Verify each generated and processed file before moving to the next production step.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Match audio parts with different durations
  • Extend drums and melodic parts using suitable methods
  • Check audio specifications before mixing
HKUDS/OpenSpace7.8천2026년 8월 13일 업데이트

Produce audio in separate stems, meaning individual instrument tracks, and verify each output as you go. Align track lengths with silence, loops, or crossfades, then apply effects, mix a master, and package the files.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Align instrument tracks to a reference audio file
  • Choose how to extend tracks that are too short
  • Verify audio properties after generation and effects
HKUDS/OpenSpace7.8천2026년 8월 13일 업데이트

Produce a master track and separate audio parts through a structured Python workflow. Apply filters and reverb, export WAV files with consistent settings, package them in a ZIP archive, and check that the deliverables meet the requested specifications.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Export a master track with separate audio parts
  • Apply filters and reverb to audio
  • Check duration and format across deliverables
HKUDS/OpenSpace7.8천2026년 8월 13일 업데이트

Keep document creation moving when web searches and page retrieval repeatedly fail. The skill preserves the original task, uses the model’s existing knowledge, and clearly identifies information that could not be checked against external sources.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Continue drafting after repeated web retrieval failures
  • Preserve task requirements during network errors
  • Mark information that could not be externally verified
HKUDS/OpenSpace7.8천2026년 8월 13일 업데이트

When Python execution repeatedly fails in execute_code_sandbox, use a file-based alternative: save the script, run it through the shell, and capture results or errors. The guidance covers paths, imports, timeouts, structured output, and optional cleanup.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Retry Python work through the shell after repeated sandbox failures
  • Run longer tasks with an adjusted timeout
  • Execute Python work that needs multiple files or system utilities
HKUDS/OpenSpace7.8천2026년 8월 13일 업데이트

Recover from repeated sandbox execution failures by saving Python code to a script and running it through run_shell. Check output, error messages, and exit codes to confirm results or diagnose remaining execution problems.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Continuing Python work after two consecutive sandbox failures
  • Switching execution methods after persistent timeouts
  • Diagnosing script failures through error output
HKUDS/OpenSpace7.8천2026년 8월 13일 업데이트

HKUDS의 스킬 모두 보기

이 스킬의 문제 신고