Redirecting on protected routes

Hey! Is there any recommended way to do route protecting on the server with SSR?

For example, I need to redirect users from protected routes to the previous URL, if exists on
router
.

Here's my current implementation:
type Session = { token: string | undefined };

const OPTIONS: SessionConfig = {
  password: process.env.SESSION_SECRET,
};

export const getSession = async () => {
  return await useSession<Session>(OPTIONS);
};

export const redirectUnauthenticated = cache(async (url: string) => {
  "use server";
  const session = await getSession();
  if (session.data.token === undefined) {
    throw redirect(url);
  }
  return {};
}, "redirectUnauthenticated");

export const createRedirectUnauthenticated = (url: string = "/login") => {
  createAsync(() => redirectUnauthenticated(url));
};

export default function Page() {
  createRedirectUnauthenticated("/login?redirect=/profile");

  return ...
}

However, this implementation is not the best because it shows the
Page
to an unauthorized user for a few milliseconds before redirecting.

In addition, if using the snippet below for the
Page
route, it won't show the
Page
to user for a few milliseconds before redirecting, but it can run the
preload
at any state of my app, which will break all redirects and always redirect to
/login?redirect=/profile
instead of the
?redirect
parameter:
export const route = {
  preload: () => createRedirectUnauthenticated("/login?redirect=/profile"),
} satisfies RouteDefinition;


Before, I tried using
useNavigate
, but the code needs to be run on the client in this case. However, I need to perform this check on the server first.

Also, as I mentioned before, I want always to redirect the unauthorized user to the previous URL. I tried doing it with
event?.router?.previousUrl
from
getRequestEvent()
in
redirectUnauthenticated
function, but it's always returns
undefied
.

How can I solve this issue correctly?
Was this page helpful?