콘텐츠로 이동

Neon Postgres & Astro

Neon은 완전 관리형 서버리스 Postgres 데이터베이스입니다. 스토리지와 컴퓨팅을 분리하여 자동 확장, 브랜칭, 그리고 무제한 스토리지를 제공합니다.

Astro에서 Neon을 사용하려면 Neon 환경 변수를 설정해야 합니다. 프로젝트 루트에서 .env 파일을 만들거나 편집하고 다음 코드를 추가하여 프로젝트 세부 정보를 대체합니다:

.env
NEON_DATABASE_URL="postgresql://<user>:<password>@<endpoint_hostname>.neon.tech:<port>/<dbname>?sslmode=require"

더 좋은 TypeScript 지원을 위해 src/env.d.ts 파일에 환경 변수를 정의하세요:

src/env.d.ts
interface ImportMetaEnv {
readonly NEON_DATABASE_URL: string;
}
interface ImportMeta {
readonly env: ImportMetaEnv;
}
Astro의 환경 변수.env 파일에 대해 자세히 알아보세요.

Neon에 연결하려면 @neondatabase/serverless 패키지를 설치합니다:

터미널 창
npm install @neondatabase/serverless

다음 코드를 사용하여 새 파일 src/lib/neon.ts를 생성하여 Neon 클라이언트를 초기화합니다:

src/lib/neon.ts
import { neon } from '@neondatabase/serverless';
export const sql = neon(import.meta.env.NEON_DATABASE_URL);

이제 Neon 클라이언트를 사용하여 모든 .astro 컴포넌트에서 데이터베이스를 쿼리할 수 있습니다. 다음은 Postgres 데이터베이스에서 현재 시간을 가져오는 예시입니다:

src/pages/index.astro
---
import { sql } from '../lib/neon';
const response = await sql`SELECT NOW() as current_time`;
const currentTime = response[0].current_time;
---
<h1>Current Time</h1>
<p>The time is: {currentTime}</p>

Neon을 사용한 데이터베이스 브랜칭

섹션 제목: “Neon을 사용한 데이터베이스 브랜칭”

Neon의 브랜칭 기능을 사용하면 개발 또는 테스트를 위해 데이터베이스의 복사본을 만들 수 있습니다. 각 브랜치에 대해 서로 다른 환경 변수를 생성하여 Astro 프로젝트에서 이 기능을 사용하세요:

.env.development
NEON_DATABASE_URL=your_development_branch_url
.env.production
NEON_DATABASE_URL=your_production_branch_url

더 많은 백엔드 서비스 가이드

기여하기 커뮤니티 후원하기