Skip to content

Commit

Permalink
made routing persitent
Browse files Browse the repository at this point in the history
  • Loading branch information
chuma-beep committed Dec 31, 2024
1 parent 9147e75 commit 95a8d6f
Show file tree
Hide file tree
Showing 4 changed files with 166 additions and 12 deletions.
4 changes: 3 additions & 1 deletion app/login/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,14 @@ import { encodedRedirect } from "@/utils/utils";
import GithubAuthenticate from "./github/GithubAuth";
import GoogleAuthenticate from "./google/GoogleAuthButton";
import Image from "next/image";
import { useSession } from 'next-auth/react'




export default function Login({ searchParams }: { searchParams: Message }) {
const supabase = createClient()


const login = async (formData: FormData) => {
"use server";

Expand Down
49 changes: 49 additions & 0 deletions middleware.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { type NextRequest } from "next/server";
import { updateSession } from "@/utils/supabase/middleware";
import { NextResponse } from "next/server";
import { createClient } from "./utils/supabase/client";
import { supabase } from './services/supabaseClient';

export async function middleware(request: NextRequest) {
return await updateSession(request);
Expand All @@ -15,6 +18,52 @@ export const config = {
* - images - .svg, .png, .jpg, .jpeg, .gif, .webp
* Feel free to modify this pattern to include more paths.
*/
'/',
'/protected',
'/login',
'/profile',
"/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)",
],
};



// // middleware.ts
// import { type NextRequest } from "next/server";
// import { NextResponse } from "next/server";
// import { createClient } from "@/utils/supabase/middleware";

// export async function middleware(request: NextRequest) {
// const { supabase, response } = createClient(request);

// // Refresh session and get current session
// const {
// data: { session },
// } = await supabase.auth.getSession();

// // Define public routes that don't require authentication
// const publicRoutes = ['/login', '/signup', '/forgot-password'];
// const isPublicRoute = publicRoutes.includes(request.nextUrl.pathname);

// // If there's no session and the route isn't public, redirect to login
// if (!session && !isPublicRoute) {
// const redirectUrl = new URL('/login', request.url);
// // Store the attempted URL to redirect back after login
// redirectUrl.searchParams.set('redirectTo', request.nextUrl.pathname);
// return NextResponse.redirect(redirectUrl);
// }

// // If there's a session and user tries to access login/signup pages,
// // redirect to protected area
// if (session && isPublicRoute) {
// // Check if there's a redirectTo parameter
// const redirectTo = request.nextUrl.searchParams.get('redirectTo');
// if (redirectTo) {
// return NextResponse.redirect(new URL(redirectTo, request.url));
// }
// // Default redirect to protected page
// return NextResponse.redirect(new URL('/protected', request.url));
// }

// return response;
// }
123 changes: 113 additions & 10 deletions utils/supabase/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,69 @@
import { createServerClient } from "@supabase/ssr";
// import { createServerClient } from "@supabase/ssr";
// import { type NextRequest, NextResponse } from "next/server";

// export const updateSession = async (request: NextRequest) => {
// // This `try/catch` block is only here for the interactive tutorial.
// // Feel free to remove once you have Supabase connected.
// try {
// // Create an unmodified response
// let response = NextResponse.next({
// request: {
// headers: request.headers,
// },
// });

// const supabase = createServerClient(
// process.env.NEXT_PUBLIC_SUPABASE_URL!,
// process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
// {
// cookies: {
// getAll() {
// return request.cookies.getAll();
// },
// setAll(cookiesToSet) {
// cookiesToSet.forEach(({ name, value }) =>
// request.cookies.set(name, value),
// );
// response = NextResponse.next({
// request,
// });
// cookiesToSet.forEach(({ name, value, options }) =>
// response.cookies.set(name, value, options),
// );
// },
// },
// },
// );

// // This will refresh session if expired - required for Server Components
// // https://supabase.com/docs/guides/auth/server-side/nextjs
// await supabase.auth.getUser();

// return response;
// } catch (e) {
// // If you are here, a Supabase client could not be created!
// // This is likely because you have not set up environment variables.
// // Check out http://localhost:3000 for Next Steps.
// return NextResponse.next({
// request: {
// headers: request.headers,
// },
// });
// }
// };








// middleware.ts
import { type NextRequest, NextResponse } from "next/server";
import { createServerClient } from "@supabase/ssr";

export const updateSession = async (request: NextRequest) => {
// This `try/catch` block is only here for the interactive tutorial.
// Feel free to remove once you have Supabase connected.
export async function updateSession(request: NextRequest) {
try {
// Create an unmodified response
let response = NextResponse.next({
Expand Down Expand Up @@ -35,21 +95,64 @@ export const updateSession = async (request: NextRequest) => {
},
);

// This will refresh session if expired - required for Server Components
// https://supabase.com/docs/guides/auth/server-side/nextjs
await supabase.auth.getUser();
// This will refresh session if expired
const { data: { user } } = await supabase.auth.getUser();

// Define public routes that don't require authentication
const publicRoutes = ['/login', '/signup', '/forgot-password'];
const isPublicRoute = publicRoutes.some(route =>
request.nextUrl.pathname.startsWith(route)
);

// If there's no user and the route isn't public, redirect to login
if (!user && !isPublicRoute) {
const redirectUrl = new URL('/login', request.url);
// Store the attempted URL to redirect back after login
redirectUrl.searchParams.set('redirectTo', request.nextUrl.pathname);
return NextResponse.redirect(redirectUrl);
}

// If there's a user and they're trying to access auth pages, redirect to protected
if (user && isPublicRoute) {
// Check if there's a redirectTo parameter
const redirectTo = request.nextUrl.searchParams.get('redirectTo');
if (redirectTo && !publicRoutes.some(route => redirectTo.startsWith(route))) {
return NextResponse.redirect(new URL(redirectTo, request.url));
}
// Default redirect to protected page
return NextResponse.redirect(new URL('/protected', request.url));
}

return response;
} catch (e) {
// If you are here, a Supabase client could not be created!
// This is likely because you have not set up environment variables.
// Check out http://localhost:3000 for Next Steps.
return NextResponse.next({
request: {
headers: request.headers,
},
});
}
};
}

// Export the middleware function
export async function middleware(request: NextRequest) {
return await updateSession(request);
}

// Export the matcher config
export const config = {
matcher: [
/*
* Match all request paths except:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
* - public folder files (images etc)
*/
'/',
'/protected',
'/login',
'/profile',
"/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)",
],
};
2 changes: 1 addition & 1 deletion utils/supabase/server.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { createServerClient } from "@supabase/ssr";
import { createServerClient, type CookieOptions } from "@supabase/ssr";
import { cookies } from "next/headers";

export const createClient = () => {
Expand Down

0 comments on commit 95a8d6f

Please sign in to comment.