flowforfrank / webtips

https://webtips.dev
1 stars 0 forks source link

how-to-set-up-protected-routes-in-your-svelte-application #12

Open utterances-bot opened 2 years ago

utterances-bot commented 2 years ago

How to Set Up Protected Routes in Your Svelte Application - Weekly Webtips

Learn how you can utilize the svelte-routing library to implement custom private routes in your Svelte application that requires authentication.

https://www.webtips.dev/how-to-set-up-protected-routes-in-your-svelte-application?ref=morioh.com&utm_source=morioh.com

zfranco55 commented 2 years ago

since I am at the beginning, I wanted to know how to implement the code in production and how the sending of the token by the client works (is it automatic or must be entered manually). is there any link that explains it, because I have not found anything that is clear to me or explained simply like your article.

flowforfrank commented 2 years ago

since I am at the beginning, I wanted to know how to implement the code in production and how the sending of the token by the client works (is it automatic or must be entered manually). is there any link that explains it, because I have not found anything that is clear to me or explained simply like your article.

Hey @zfranco55, Unfortunately, I don't have a tutorial for production ready-code, however, I can give you some code piece to help you better understand how this would work in production. Basically you want to make a request for your server when authenticating the user that should send back a valid token if the user authenticated successfully:

fetch('public-api')
    .then(response => response.json())
    .then(data => {
        // Set the token received from your server
        localStorage.setItem('token', data.token);
    });

// Later in your app you can use it as a header to authenticate subsequent requests
fetch('private-api',  {
    method: 'GET',
    headers: { 'token': localStorage.getItem('token') }
});

Then you want to set this token in either a cookie, or as shown in the above code example, in local storage. For subsequent requests that requires authentication, you can send this token along with your request to let your server know that the request is authenticated.

If you are interested in more on server-side authentication, I have a tutorial on how you can do that in Express with JWT, you can find it here: How to Secure Your API With JSON Web Tokens