Skip to content

Commit

Permalink
Set up redirects in middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
delbaoliveira committed Mar 14, 2024
1 parent 1cca22a commit f58caff
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 10 deletions.
7 changes: 4 additions & 3 deletions app/auth/01-auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,8 @@ export async function signup(

// 5. Create a session for the user
if (data && data.length > 0) {
const user = data[0];
await createSession(user.id);
const userId = data[0].id.toString();
await createSession(userId);
}
} catch (error) {
return {
Expand Down Expand Up @@ -105,7 +105,8 @@ export async function login(
}

// 5. If login successful, create a session for the user
await createSession(user.id);
const userId = user.id.toString();
await createSession(userId);
} catch (error) {
return errorMessage;
}
Expand Down
7 changes: 0 additions & 7 deletions app/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import type { Metadata } from 'next';
import { Inter } from 'next/font/google';
import './globals.css';
import { verifyClientSession, verifyServerSession } from '@/lib/session';

const inter = Inter({ subsets: ['latin'] });

Expand All @@ -15,12 +14,6 @@ export default async function RootLayout({
}: Readonly<{
children: React.ReactNode;
}>) {
// This is for quick testing, we shouldn't verify the session in a layout
const x = await verifyClientSession();
const y = await verifyServerSession();
console.log(x);
console.log(y);

return (
<html lang="en">
<body className={`${inter.className} dark:bg-black dark:text-white`}>
Expand Down
42 changes: 42 additions & 0 deletions middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { NextRequest, NextResponse } from 'next/server';
import { verifyClientSession } from '@/app/auth/02-client-session';

// Client Sessions can be verified in Middleware
// as we're only checking for a cookie in the headers
// and there are no data requests to block the stream

// We should avoid verifying Server Sessions in Middleware
// since we're making a data request on every route change
// 👆 This is especially important with Next.js Route prefetching
// multiple middleware calls can be triggered on a single route change

// 1. Specify all protected routes
const protectedRoutes = ['/dashboard'];
// 2. Specify **only** the public paths that should redirect if user is authed
const publicRoutes = ['/login', '/signup', '/'];

export default async function middleware(req: NextRequest) {
// 3. Get the token from the request
const session = req.cookies.get('session')?.value;
const { isAuth } = (await verifyClientSession(session)) || {};

// 4. Check if the current route is protected or public
const path = req.nextUrl.pathname;
const isProtectedRoute = protectedRoutes.includes(path);
const isPublicRoute = publicRoutes.includes(path);

// 5. Redirect based on the user's auth status
if (isProtectedRoute && !isAuth) {
return NextResponse.redirect(new URL('/login', req.nextUrl));
}

if (
isPublicRoute &&
isAuth &&
!req.nextUrl.pathname.startsWith('/dashboard')
) {
return NextResponse.redirect(new URL('/dashboard', req.nextUrl));
}

return NextResponse.next();
}

0 comments on commit f58caff

Please sign in to comment.