I'm facing difficulties while migrating from Nuxt 2 to Nuxt 3, and I have a question.
Currently, in Nuxt 2, I am handling authentication through middleware. As you can see in the code below, I am using app to work with cookies and Axios. However, it seems that in Nuxt 3, there is no app.
How should I modify this code for Nuxt 3?
// middleware/auth.js
export default async function (app) {
try {
console.log('Loading...');
const csrfToken = await fetchCsrfToken(app);
const authResult = await checkAuth(app, "accessToken", csrfToken);
app.store.commit('setAuthResult', authResult.res);
if(authResult.res){
const userInfo = await getUserInfo(app, csrfToken);
app.store.commit('setUserInfo', userInfo.res);
console.log(userInfo);
}
} catch (error) {
console.error('Error during authentication check:', error);
}
}
function ajaxRequest(app, url, method, data) {
const headers = {
'Content-Type': 'application/json',
};
if (data) {
if (data.token) {
headers.Authorization = `Bearer ${data.token}`;
}
if (data.csrfToken) {
headers['X-XSRF-TOKEN'] = data.csrfToken;
}
}
const axiosConfig = {
method,
url,
headers,
data,
};
return new Promise((resolve, reject) => {
app.$axios(axiosConfig)
.then((response) => {
if (response.status === 200) {
resolve(response.data);
} else {
switch (response.status) {
case 400:
reject(new Error('Bad Request: ' + response.data));
break;
case 401:
reject(new Error('Unauthorized: ' + response.data));
break;
case 403:
reject(new Error('Forbidden: ' + response.data));
break;
default:
reject(new Error('Request failed with status: ' + response.status));
}
}
})
.catch((error) => {
reject(new Error('Request error: ' + error));
});
});
}
async function fetchCsrfToken(app) {
try {
const response = await app.$axios.$get('/getcsrf');
const tokenInfo = response.token;
console.log('CSRF token stored in Cookies:', tokenInfo);
return tokenInfo;
} catch (error) {
console.error('Error fetching CSRF token:', error);
throw error;
}
}
async function checkAuth(app, tokenType, csrfToken) {
let token;
if (tokenType === 'accessToken') {
token = app.$cookies.get('accessToken');
} else if (tokenType === 'refreshToken') {
token = app.$cookies.get('refreshToken');
} else {
console.error('Invalid tokenType:', tokenType);
return;
}
try {
console.log(tokenType + " call");
const res = await ajaxRequest(app, '/check-auth', 'POST', {
token,
csrfToken,
});
if (tokenType === 'accessToken' && res === 'Refresh token required') {
await checkAuth(app, 'refreshToken', csrfToken);
return false;
}
return {res};
} catch (error) {
console.error('Error checking authentication:', error);
}
}
async function getUserInfo(app, csrfToken) {
const token = app.$cookies.get('accessToken');
try {
const res = await ajaxRequest(app, "/user-info", "POST", {
token,
csrfToken,
});
return {res};
} catch (error) {
console.error('Error checking authentication:', error);
}
}
There is a method useNuxtApp
:
export default defineNuxtRouteMiddleware(() => {
const nuxt = useNuxtApp(); // nuxt app is here
const vue = nuxt.vueApp; // vue app is here
});