Get intended URL a "use server" query is called from

I have a query that gets a user's info and redirects if they aren't logged in. I want add a redirectUrl parameter to the login page and return them to their intended url. Using the referer header works if I visit the URL directly, but for client-side navigation using a <A> or navigate() the referer header is from before the navigation completes. Currently, I am passing the path as a parameter to the query. Is there a better way to do this? One small downside is since the query is called with different keys, the cached value isn't used. Mainly I'd like to avoid manually passing the current path everywhere I use the query.
1 Reply
Madaxen86
Madaxen862mo ago
I would recommend not to redirect from a query. Queries are to fetch data. What I like to do is have a query (returning true or false) that refreshes the users session which I call in a layout that wraps all pages which require authentication. In the layout I have a
<Show when={refreshed() === false}><Navigate href={"/login?redirectTo=" + location.pathname} />

<Show when={refreshed() === false}><Navigate href={"/login?redirectTo=" + location.pathname} />

Full example: https://discord.com/channels/722131463138705510/1374549937836265625/1374625581571903538

Did you find this page helpful?