Skip to content

fix: add protected routes with auth middleware #25

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 11, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 10 additions & 9 deletions src/app/(app)/_components/header/user-dropdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,18 @@ import { useSession } from 'next-auth/react';
import { useState } from 'react';

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

const [isLoggingOut, setIsLoggingOut] = useState(false);
async function handleLogout() {
try {
setIsLoggingOut(true);
await signOutAction({ redirectTo: '/login' });
} finally {
setIsLoggingOut(false);
}
}

return (
<DropdownMenu>
Expand All @@ -45,14 +53,7 @@ export default function UserDropdown() {
</DropdownMenuShortcut>
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
className="cursor-pointer"
disabled={isLoggingOut}
onClick={async () => {
setIsLoggingOut(true);
await signOutAction({ redirectTo: '/login' });
}}
>
<DropdownMenuItem className="cursor-pointer" onClick={handleLogout} disabled={isLoggingOut}>
Log out
<DropdownMenuShortcut>
{isLoggingOut ? (
Expand Down
20 changes: 18 additions & 2 deletions src/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,22 @@
export { auth as middleware } from '@/auth';
import { auth } from '@/auth';

const PROTECTED_ROUTES = [
{ path: '/new', exact: true },
{ path: '/@', exact: false },
];

export default auth((req) => {
const { pathname } = req.nextUrl;
const isProtected = PROTECTED_ROUTES.some(({ path, exact }) =>
exact ? pathname === path : pathname.startsWith(path),
);

if (!req.auth && isProtected) {
const loginUrl = new URL('/login', req.url);
return Response.redirect(loginUrl);
}
});

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