Skip to content

Commit

Permalink
Create a logout workflow with server action
Browse files Browse the repository at this point in the history
  • Loading branch information
Eprince-hub committed Oct 23, 2024
1 parent 873a76c commit 1d8c825
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
6 changes: 6 additions & 0 deletions app/(auth)/logout/LogoutButton.module.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
.logoutButton {
padding: 0.25rem 0.5rem;
background: transparent;
border: none;
font-size: 1.125rem;
}
22 changes: 22 additions & 0 deletions app/(auth)/logout/LogoutButton.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
'use client';

import { useRouter } from 'next/navigation';
import { logout } from './action';
import styles from './LogoutButton.module.scss';

export function LogoutButton() {
const router = useRouter();
return (
<form>
<button
className={styles.logoutButton}
formAction={async () => {
await logout();
router.refresh();
}}
>
logout
</button>
</form>
);
}
19 changes: 19 additions & 0 deletions app/(auth)/logout/action.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
'use server';

import { cookies } from 'next/headers';
import { deleteSession } from '../../../database/sessions';

export async function logout() {
// Task: Implement the user logout workflow

// 1. Get the session token from the cookie
const cookieStore = await cookies();

const session = cookieStore.get('sessionToken');

// 2. Delete the session from the database based on the token
if (session) await deleteSession(session.value);

// 3. Delete the session cookie from the browser
cookieStore.delete('sessionToken');
}

0 comments on commit 1d8c825

Please sign in to comment.