# Gửi với Next. js

> Gửi từ Route Handler để khóa không bao giờ đến được trình duyệt.

## Điều kiện trước

- Một Sendtern [khóa API](https://sendtern.com/docs/authentication) được lưu như `SENDTERN_API_KEY`
- A Next.js 13.4+ app using the App Router

1. **Thêm khóa**: Thêm khóa vào `.env.local`. Đừng đặt tiền tố `NEXT_PUBLIC_`, vì nó sẽ làm cho trình duyệt thấy.

```
SENDTERN_API_KEY=st_your_api_key
```

2. **Create a Route Handler**: Create `app/api/send/route.js`. It runs on the server only.

```
// app/api/send/route.js
export async function POST(request) {
  const { email } = await request.json();

  const res = await fetch("https://sendtern.com/emails", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.SENDTERN_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      from: "Acme <hello@mail.example.com>",
      to: [email],
      subject: "Welcome to Acme",
      html: "<p>Thanks for signing up.</p>",
    }),
  });

  return Response.json(await res.json(), { status: res.status });
}
```

3. **Kiểm tra phản ứng**: Một yêu cầu thành công sẽ trả lại `200 OK` với id email. Dùng nó để tìm email sau này.

```
{
  "id": "47be30ca-24b7-48fb-b35d-ff287b89e66d"
}
```

> **tip:** Thay thế người gửi ví dụ bằng một địa chỉ trên [domain xác thực](https://sendtern.com/docs/domains) của bạn.
