Skip to content

Commit 6b272ee

Browse files
authored
fix: add protected routes with auth middleware (#25)
1 parent f53e4f2 commit 6b272ee

File tree

2 files changed

+28
-11
lines changed

2 files changed

+28
-11
lines changed

src/app/(app)/_components/header/user-dropdown.tsx

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,18 @@ import { useSession } from 'next-auth/react';
1616
import { useState } from 'react';
1717

1818
export default function UserDropdown() {
19+
const [isLoggingOut, setIsLoggingOut] = useState(false);
1920
const { data: session } = useSession();
2021
const { username, name, email, image } = session?.user ?? {};
2122

22-
const [isLoggingOut, setIsLoggingOut] = useState(false);
23+
async function handleLogout() {
24+
try {
25+
setIsLoggingOut(true);
26+
await signOutAction({ redirectTo: '/login' });
27+
} finally {
28+
setIsLoggingOut(false);
29+
}
30+
}
2331

2432
return (
2533
<DropdownMenu>
@@ -45,14 +53,7 @@ export default function UserDropdown() {
4553
</DropdownMenuShortcut>
4654
</DropdownMenuItem>
4755
<DropdownMenuSeparator />
48-
<DropdownMenuItem
49-
className="cursor-pointer"
50-
disabled={isLoggingOut}
51-
onClick={async () => {
52-
setIsLoggingOut(true);
53-
await signOutAction({ redirectTo: '/login' });
54-
}}
55-
>
56+
<DropdownMenuItem className="cursor-pointer" onClick={handleLogout} disabled={isLoggingOut}>
5657
Log out
5758
<DropdownMenuShortcut>
5859
{isLoggingOut ? (

src/middleware.ts

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,22 @@
1-
export { auth as middleware } from '@/auth';
1+
import { auth } from '@/auth';
2+
3+
const PROTECTED_ROUTES = [
4+
{ path: '/new', exact: true },
5+
{ path: '/@', exact: false },
6+
];
7+
8+
export default auth((req) => {
9+
const { pathname } = req.nextUrl;
10+
const isProtected = PROTECTED_ROUTES.some(({ path, exact }) =>
11+
exact ? pathname === path : pathname.startsWith(path),
12+
);
13+
14+
if (!req.auth && isProtected) {
15+
const loginUrl = new URL('/login', req.url);
16+
return Response.redirect(loginUrl);
17+
}
18+
});
219

3-
// optionally, don't invoke middleware on some paths
420
export const config = {
521
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
622
};

0 commit comments

Comments
 (0)