Friday 5 May 2023

How to access a cookie created via Sveltkit cookies from axios interceptor

I've got a Login form with the following action (login/+page.server.js):

export const actions = {

    default: async ({ request, cookies }) => {

        const data = Object.fromEntries(await request.formData());
        
        // validate and create DTO.
        const loginData = loginDTO(data);

        // if errors returned from building the DTO (validation errors) then return the object.
        if (loginData?.errors && !emptyObject(loginData.errors)) {
            return {
                "data": loginData.data,
                "errors": loginData.errors,
            };
        }


        // perform call to log in a user.
        const response = await login(loginData);
        // const response = await loginUser(loginData);
        if (response.success) {
            // save token to a cookie
            cookies.set(
                'token',
                response.res.data.data,
                {
                    path: '/',
                    maxAge: 60 * 60 * 25 * 365,
                    httpOnly: false,
                    secure: false,
                }
            )

            throw redirect(302, '/')
        }

        return {
            "data": loginData.data,
            "errors": response.errors,
        }
    }
}

basically this is making a request to the backend authenticating a user an a JWT token is returned. So far so good, the token is returned and using Sveltekit's cookies I can successfully set the cookie, when I inspect Chrome's application tab (in dev tools) I can see the cookie there.

dev tools img

Now, I need to attach the value of the cookie to my requests. I'm using axios. To do so I created an interceptor:

import axios from "axios";
import Cookies from "js-cookie";

// let Cookies2 = Cookies.noConflict();
export const app = axios.create({
    baseURL: "http://127.0.0.1:8080/api/v1",
    timeout: 1000,
    params: {},
    // withCredentials: true,
})
// Request interceptor. Whenever a new request goes out it will be caught
// by the interceptor and whatever code is defined will be executed before continuing its flow.
app.interceptors.request.use(
    config => {
        
        console.log("here in http middleware...")
        let token = Cookies.get()
        console.log("token: ", token);
        config.headers['Content-Type'] = 'application/json';
        return config;
    },
    error => {
        Promise.reject(error)
    }
);

But I've got a couple issues:

  1. I haven't been able to use Sveltekit's cookies object, don't know how to import it here.
  2. Since the cookie is visible client-side, I decided to install js-cookie to access it, but the log statement I've got in the interceptor is always coming back empty, meaning that it's not picking up the cookie.

Any idea what's going on? or any other way I can achieve what I'm trying to do?

I could also scrap the whole cookies approach and simply use a store, what are the cons and pros of each approach?

Thanks.



from How to access a cookie created via Sveltkit cookies from axios interceptor

No comments:

Post a Comment