Next.js Discord

Discord Forum

Can you use a server layout component inside a route group instead of middleware?

Answered
Australian Freshwater Crocodile posted this in #help-forum
Open in Discord
Avatar
Australian Freshwater CrocodileOP
Middleware seems very complicated to me, could you just use a layout server component inside a route group instead?

// app/(auth)/layout.tsx
"use server";

import { createClient } from "@/utils/supabase/server";
import { redirect } from "next/navigation";

export default async ({ children }: { children?: React.ReactNode }) => {
  const supabase = await createClient();

  const {
    data: { user },
  } = await supabase.auth.getUser();

  if (!user) return redirect("/");

  return <>{children}</>;
};
Answered by Australian Freshwater Crocodile
"Since Server Components can't write cookies, you need middleware to refresh expired Auth tokens and store them."
View full answer

19 Replies

Avatar
@James4u yeah, I think this is recommended approach according to the supabase docs
Avatar
Australian Freshwater CrocodileOP
supabase docs recommend middleware from what i see?
Avatar
to summarize your approach is correct
wait thats the same
Avatar
see the last step - how to protect the private page
Avatar
Australian Freshwater CrocodileOP
does not having middleware effect anything?
Avatar
Australian Freshwater CrocodileOP
"Since Server Components can't write cookies, you need middleware to refresh expired Auth tokens and store them."
Answer
Avatar
Australian Freshwater CrocodileOP
Oh maybe thats why?
Avatar
@Australian Freshwater Crocodile Oh maybe thats why?
Avatar
yeah, doc clearly says that
Avatar
Australian Freshwater CrocodileOP
Well my question was if you can only use the server component guard, but due to that sentence I see why you should also use the middleware. I assume that eventually the session in the cookie will expire and then not work because it would never be able to set a new cookie.
Avatar
nah
Avatar
I would like to add that you should never use a layout as an auth check. Due to how next bundles and serves pages they are able to be fetched without the layout meaning that if someone knows what they are doing and auth is only checked in the layout they will be able to see the content on the page that should be for authenticated users only.
Preferably authenticate at the data source, but if not possible, do it at the page level.