Skip to content

Commit

Permalink
Merge pull request #179 from h8570rg/fix/middleware
Browse files Browse the repository at this point in the history
fix: middleware
  • Loading branch information
h8570rg authored Aug 3, 2024
2 parents 4a44a60 + 1e13ed6 commit 3ceae73
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 55 deletions.
103 changes: 59 additions & 44 deletions lib/utils/supabase/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,53 +1,68 @@
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,
},
});
/** @see https://supabase.com/docs/guides/auth/server-side/nextjs */
export async function updateSession(request: NextRequest) {
let supabaseResponse = NextResponse.next({
request,
});

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),
);
},
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),
);
supabaseResponse = NextResponse.next({
request,
});
cookiesToSet.forEach(({ name, value, options }) =>
supabaseResponse.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();
// IMPORTANT: Avoid writing any logic between createServerClient and
// supabase.auth.getUser(). A simple mistake could make it very hard to debug
// issues with users being randomly logged out.

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,
},
});
const {
data: { user },
} = await supabase.auth.getUser();

if (
!user &&
!request.nextUrl.pathname.startsWith("/login") &&
!request.nextUrl.pathname.startsWith("/sign-up") &&
!request.nextUrl.pathname.startsWith("/auth-code-error") &&
!request.nextUrl.pathname.startsWith("/api/auth")
) {
// no user, potentially respond by redirecting the user to the login page
const url = request.nextUrl.clone();
url.pathname = "/login";
return NextResponse.redirect(url);
}
};

// IMPORTANT: You *must* return the supabaseResponse object as it is. If you're
// creating a new response object with NextResponse.next() make sure to:
// 1. Pass the request in it, like so:
// const myNewResponse = NextResponse.next({ request })
// 2. Copy over the cookies, like so:
// myNewResponse.cookies.setAll(supabaseResponse.cookies.getAll())
// 3. Change the myNewResponse object to fit your needs, but avoid changing
// the cookies!
// 4. Finally:
// return myNewResponse
// If this is not done, you may be causing the browser and server to go out
// of sync and terminate the user's session prematurely!

return supabaseResponse;
}
12 changes: 1 addition & 11 deletions middleware.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,6 @@
import { type NextRequest } from "next/server";
import { updateSession } from "./lib/utils/supabase/middleware";

// TODO: 見直し
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const noAuthRoutes = [
"/auth-code-error",
"/login",
"/sign-up",
"/api/auth/callback",
"/manifest.json",
];

/**
* @see https://supabase.com/docs/guides/auth/server-side/creating-a-client?environment=middleware
* @see https://supabase.com/docs/guides/auth/server-side/nextjs
Expand All @@ -33,6 +23,6 @@ export const config = {
* - favicon.ico (favicon file)
* Feel free to modify this pattern to include more paths.
*/
"/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)",
"/((?!_next/static|_next/image|favicon.ico|manifest.json|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)",
],
};

0 comments on commit 3ceae73

Please sign in to comment.