admin管理员组文章数量:1204384
I have a middleware.ts
file defined in my nextjs app. In it I am able to set necessary things like authentication, etc.
I would like to also check the results of my request. I cannot seem to find a way to trigger code to run after the request. Ideally it has both the request and response object.
I need to validate that based on the parameters that came in, the request generated a valid response. If it did not, I need to throw an error and roll back the entire transaction.
I have a middleware.ts
file defined in my nextjs app. In it I am able to set necessary things like authentication, etc.
I would like to also check the results of my request. I cannot seem to find a way to trigger code to run after the request. Ideally it has both the request and response object.
I need to validate that based on the parameters that came in, the request generated a valid response. If it did not, I need to throw an error and roll back the entire transaction.
Share Improve this question asked Jan 20 at 15:57 corsiKacorsiKa 82.6k26 gold badges159 silver badges207 bronze badges 01 Answer
Reset to default 0I don't think you can achieve that with nextjs middleware, but you could do it using a http library like axios. It sounds that you want to set up something like an "Error intercerpetor"
Create an axios instance
const apiClient = axios.create({
baseURL: 'https://your-api-url.com',
timeout: 5000,
});
apiClient.interceptors.request.use(
(config) => {
// set up your configs or modify the request
return config;
},
(error) => {
// Handle request errors
return Promise.reject(error);
}
);
Add response interceptor
apiClient.interceptors.response.use(
(response) => {
// Validate response
if (!response.data.success || !response.data.data) {
// do something with the error like your rollback logic
throw new Error('Invalid response data');
}
return response;
},
(error) => {
console.error('Response Error:', error);
return Promise.reject(error);
}
);
Hope this works for you!
本文标签: nextjsRun middleware after requestStack Overflow
版权声明:本文标题:next.js - Run middleware after request - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738684377a2106739.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论