← Back to patterns

getRequestEvent & auth

Cookies, headers and per-function auth checks inside remote functions

Pattern Usage:

function requireUser() {
  const user = getRequestEvent().cookies.get('user');
  if (!user) error(401, 'Please log in first');
  return user;
}

export const getSecret = query(async () => {
  const user = requireUser(); // every remote fn checks itself
  return `Hi ${user}`;
});

export const login = form(schema, async ({ name }) => {
  getRequestEvent().cookies.set('user', name, { path: '/' });
  void getSession().refresh();
  void getSecret().refresh();
});

// in a query this throws, pass it as an argument instead:
getRequestEvent().url

Live Demo:

getSecret()

loading…

What the server sees

url in a query: remote_request_property Cannot access `event.url` in a query. Pass the value as an argument to the query instead https://svelte.dev/e/kit/remote_request_property

How it works: getRequestEvent() from $app/server gives remote functions access to cookies, headers and locals. Cookies can be read everywhere but only set in forms and commands.

Every remote function is a public HTTP endpoint, so each one checks auth itself. A shared helper like requireUser() keeps that short. Queries and forms may redirect(); commands can't, so they throw error(401), which arrives as a typed App.Error. Since SvelteKit 3, reading url, params or route inside a query throws, so that query results don't depend on which page called them.