Skip to content

Neon Postgres 和 Astro

Neon 是一个完全托管的无服务器 Postgres 数据库。它将存储和计算分开,以提供自动缩放、分支和无底存储。

¥Neon is a fully managed serverless Postgres database. It separates storage and compute to offer autoscaling, branching, and bottomless storage.

将 Neon 添加到你的 Astro 项目

标题部分 将 Neon 添加到你的 Astro 项目

¥Adding Neon to your Astro project

¥Prerequisites

  • 具有已创建项目的 Neon 账户

  • Neon 数据库连接字符串

  • 启用了 按需渲染 (SSR) 的 Astro 项目

¥Environment configuration

要将 Neon 与 Astro 一起使用,你需要设置一个 Neon 环境变量。在你的项目根目录中创建或编辑 .env 文件,并添加以下代码,替换你自己的项目详细信息:

¥To use Neon with Astro, you will need to set a Neon environment variable. Create or edit the .env file in your project root, and add the following code, replacing your own project details:

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

为了获得更好的 TypeScript 支持,请在 src/env.d.ts 文件中定义环境变量:

¥For better TypeScript support, define environment variables in a src/env.d.ts file:

src/env.d.ts
interface ImportMetaEnv {
readonly NEON_DATABASE_URL: string;
}
interface ImportMeta {
readonly env: ImportMetaEnv;
}
Learn more about environment variables and .env files in Astro.

¥Installing dependencies

安装 @neondatabase/serverless 包以连接到 Neon:

¥Install the @neondatabase/serverless package to connect to Neon:

终端窗口
npm install @neondatabase/serverless

¥Creating a Neon client

使用以下代码创建一个新文件 src/lib/neon.ts 来初始化你的 Neon 客户端:

¥Create a new file src/lib/neon.ts with the following code to initialize your Neon client:

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

¥Querying your Neon database

你现在可以使用 Neon 客户端从任何 .astro 组件查询数据库。以下示例从 Postgres 数据库获取当前时间:

¥You can now use the Neon client to query your database from any .astro component. The following example fetches the current time from the Postgres database:

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 进行数据库分支

¥Database branching with Neon

Neon 的分支功能允许你创建数据库的副本以进行开发或测试。通过为每个分支创建不同的环境变量,在你的 Astro 项目中使用它:

¥Neon’s branching feature lets you create copies of your database for development or testing. Use this in your Astro project by creating different environment variables for each branch:

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

¥Resources

更多后端服务指南

Astro 中文网 - 粤ICP备13048890号