mirror of
https://github.com/LukeHagar/website.git
synced 2025-12-10 21:07:46 +00:00
59 lines
2.4 KiB
Plaintext
59 lines
2.4 KiB
Plaintext
---
|
|
layout: tutorial
|
|
title: Initialize SDK
|
|
description: Add authentication to a Next.js project using Appwrite.
|
|
step: 3
|
|
---
|
|
Before you can use Appwrite, you need to create the Appwrite `Client` and set the project ID and endpoint.
|
|
The client is then used to create services like `Databases` and `Account`, so they all point to the same Appwrite project.
|
|
|
|
Create a function to build services you need in a file like `src/lib/server/appwrite.js` and **exporting the instances**.
|
|
|
|
As part of the function, set the current user's session if they are logged in. This is done by accessing the session cookie from the request and calling the `setSession(session)` with the cookie value.
|
|
|
|
```js
|
|
// src/lib/server/appwrite.js
|
|
import { Client, Account } from "node-appwrite";
|
|
import { parseCookie } from "next/dist/compiled/@edge-runtime/cookies";
|
|
|
|
export const SESSION_COOKIE = "a_session";
|
|
|
|
export function createAppwriteClient(headers) {
|
|
const client = new Client()
|
|
.setEndpoint(process.env.NEXT_PUBLIC_APPWRITE_ENDPOINT!)
|
|
.setProject(process.env.NEXT_PUBLIC_APPWRITE_PROJECT_ID!);
|
|
|
|
// Set the API key for the client, bypassing rate limiting and enabling
|
|
client.setKey(process.env.APPWRITE_KEY!);
|
|
|
|
// Extract the session from cookies and use it for the client
|
|
const cookies = parseCookie(headers.get("cookie") ?? "");
|
|
const session = cookies.get(SESSION_COOKIE);
|
|
if (session) client.setSession(session);
|
|
|
|
return {
|
|
get account() {
|
|
return new Account(client);
|
|
},
|
|
};
|
|
}
|
|
```
|
|
|
|
`APPWRITE_KEY`, `NEXT_PUBLIC_APPWRITE_ENDPOINT` and `NEXT_PUBLIC_APPWRITE_PROJECT` are environment variables that are exported in your project's [.env file](https://nextjs.org/docs/app/building-your-application/configuring/environment-variables).
|
|
|
|
You can get the values for these variables from the Appwrite console. The `PUBLIC_APPWRITE_ENDPOINT` is the endpoint of your Appwrite server, and the `PUBLIC_APPWRITE_PROJECT` is the ID of the project you want to use. The `APPWRITE_KEY` is an Appwrite API key with the necessary permissions to read and write to the database.
|
|
|
|
For this tutorial you'll need an API key with the following scopes:
|
|
- `accounts.read`
|
|
- `accounts.write`
|
|
- `sessions.read`
|
|
- `sessions.write`
|
|
|
|
For example, your `.env` might look something similar to this.
|
|
|
|
```text
|
|
APPWRITE_KEY=<YOUR_API_KEY>
|
|
PUBLIC_APPWRITE_ENDPOINT=https://cloud.appwrite.io/v1
|
|
PUBLIC_APPWRITE_PROJECT=<YOUR_PROJECT_ID>
|
|
```
|