Skip to content

Proper way to do auth in sveltekit? #2858

@bojanv55

Description

@bojanv55

Describe the problem

I have an app using sveltekit + java as backend. I use @sveltejs/adapter-static to pack svelte app and serve it from java server as .html files. I'm using simplest JWT token stored in cookie to do auth on the server. The question I have is - what is the proper way to do auth in this case?

This is option 1:

image

Here, client requests the page, and if he does not provide proper "Cookie: access_token=jwttokenhere" in the header, java server will redirect him directly to the /auth/login page and then the client will get that URL from sveltekit built files.

The problems I have here:

  • If I issue goto("/"); command inside the sveltekit route, svelte does not care if user is authorized or not, it will redirect no matter what. So I have to use instead
if(browser){
  window.location.href = "/";
}

Option 2:

image

Here, index page is loaded from the server without any check if user authenticated or not. Then sveltekit needs somehow to know if user is authenticated. I saw that we can use here this method export async function load({ page, fetch, session, stuff }) as an interceptor, and check if some variable is set - if not then we redirect. So here, there is no logic from the server related to redirects - server would only return status codes 401 if not authorized.

The problems I see here:

  • Even if that variable on client side is set - that doesn't mean that client is currently authenticated on the server (eg. jwt token expired etc). Then on the next fetch to the server, server will issue 401.
  • If I put fetch call inside this load function just to fetch whoami endpoint for example - in order to see if currently authenticated - this is costly on every route change.

Describe the proposed solution

No solution. Just asking what are possible alternatives to described use-cases.

Alternatives considered

No response

Importance

nice to have

Additional Information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions