Reputation: 73
I'm trying to implement JWT authentication in a SvelteKit-app and I'm having trouble with where in the code I should refresh my accesstoken on site-reload. According to what I have found I should store the JWT in memory and then have a refresh-token that is stored as a HTTP-only cookie. When the page is reloaded or opened in a new tab, I need to call my backend to see if the refresh-token is valid or not, if it is, I will generate a new JWT and return it to the client.
Where is a good idea to make this call? I was thinking that the getSession
-hook would be a good place but I'm not able to use fetch
from there.
Upvotes: 7
Views: 3465
Reputation: 17903
HTTP-only cookies must be set via the Set-Cookie
header. SvelteKit only has a few places where you can set response headers:
handle()
hook.getSession()
is probably not a good choice. The main purpose of this hook is create a sanitized version of the server context
for the browser (like remove sensitive information like passwords/API keys.) It is called after the handle()
hook, so it would be too late for setting any headers in the response.
getContext()
may be a better choice because it is called before the handle()
hook. So it is possible to get the refresh token and store it in the context until handle()
sends it as a header. The context is accessible from handle()
as request.context
Although not well-documented, fetch
is available from all of these hooks. Simply add node-fetch
as a dependency in package.json
(not a devDependency!).
I think a problem with refreshing the token in the hooks is refreshing will happen on every request. This may add unnecessary overhead to your app.
I think the best solution is to wrap any API calls that need JWT tokens as SvelteKit endpoints. If the API call fails due to a stale token, the endpoint can get a new token and send it to the browser via Set-Cookie
in the response headers. Note for this to work, you must ensure the endpoint is being called by the browser (not the server.) SvelteKit templates are executed first on the server, then again in the browser. If the endpoint is called from the server, the browser cookie will not be set.
Upvotes: 8