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 0
Add a comment  | 

1 Answer 1

Reset to default 0

I 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