mirror of
https://github.com/LukeHagar/website.git
synced 2025-12-10 12:57:49 +00:00
38 lines
1.2 KiB
Plaintext
38 lines
1.2 KiB
Plaintext
---
|
|
layout: tutorial
|
|
title: Get the logged in user
|
|
description: Add authentication to a Next.js project using Appwrite.
|
|
step: 4
|
|
---
|
|
|
|
Build a utility function to get the logged in user from Appwrite. This function will be used in our components and routes to check if a user is logged in, and access the user's details.
|
|
|
|
Edit the `src/server/appwrite.js` file to create a new function called `getLoggedInUser`.
|
|
```js
|
|
// ... your createAppwriteClient function
|
|
|
|
export async function getLoggedInUser(account) {
|
|
try {
|
|
return await account.get();
|
|
} catch {}
|
|
}
|
|
```
|
|
|
|
Now, use the `getLoggedInUser` function in the home page to redirect based on the user's login status. Create a new file in the `app` directory called `+page.jsx`.
|
|
|
|
```js
|
|
import { createSessionClient, getLoggedInUser } from "@/lib/server/appwrite";
|
|
import { headers } from "next/headers";
|
|
import { redirect } from "next/navigation";
|
|
|
|
export default async function Home() {
|
|
const { account } = createSessionClient(headers());
|
|
|
|
const user = await getLoggedInUser(account);
|
|
if (!user) redirect("/signin");
|
|
|
|
redirect("/account");
|
|
}
|
|
```
|
|
|
|
When a user visits the home page, they will be redirected to the sign in page if they are not logged in, or to the account page if they are logged in. |