nblshi
nblshi
NNuxt
Created by nblshi on 7/24/2024 in #❓・help
How can I redirect from server api?
I’ve set up Axios in the server/api folder, and my APIs are working well for fetch, update, delete, etc. However, I’m facing an issue with token expiration. When the token expires, API will returns an error, and I want to redirect the user to the home page so they can log in again. I’ve used Axios interceptors to detect the error and log it to the console, but I’m stuck on the redirect part. I can’t use useRoute, redirect, or navigateTo due to the error "vue app aliases are not allowed in server runtime." Is there a workaround for handling redirects in this scenario?
import axios from 'axios';
import packageJson from '~/package.json';

const config = useRuntimeConfig();

// ---------- dynamic
interface EnvironmentConfigs {
[key: string]: string;
}

const environmentConfigs: EnvironmentConfigs = {
development: config.developmentBaseurl,
staging: config.stagingBaseurl,
production: config.productionBaseurl
};

const baseURL = environmentConfigs[packageJson.environment_config];

if (!baseURL) {
throw new Error('Invalid environment configuration');
}

export const devApiClient = axios.create({
baseURL,
})

// Add response interceptor to handle token expiration
devApiClient.interceptors.response.use(
(response) => {
// Do something with response data
return response;
},
(error) => {
// Do something with response error
if (error.response.data === 'Unauthorized: Invalid or expired token\n') {
console.error('Token expired, redirecting to login page...');
}

return Promise.reject(error);
}
);
import axios from 'axios';
import packageJson from '~/package.json';

const config = useRuntimeConfig();

// ---------- dynamic
interface EnvironmentConfigs {
[key: string]: string;
}

const environmentConfigs: EnvironmentConfigs = {
development: config.developmentBaseurl,
staging: config.stagingBaseurl,
production: config.productionBaseurl
};

const baseURL = environmentConfigs[packageJson.environment_config];

if (!baseURL) {
throw new Error('Invalid environment configuration');
}

export const devApiClient = axios.create({
baseURL,
})

// Add response interceptor to handle token expiration
devApiClient.interceptors.response.use(
(response) => {
// Do something with response data
return response;
},
(error) => {
// Do something with response error
if (error.response.data === 'Unauthorized: Invalid or expired token\n') {
console.error('Token expired, redirecting to login page...');
}

return Promise.reject(error);
}
);
1 replies