Nuxtjs ERROR Cannot set headers after they are sent to the client

I just created a middleware that checks for token and put in cookies after getting and also since there is no api for getting the profile, I used the api for getting specific data and when the status has an response like Please login first it will redirect to login page.

Here is what I tried

//authentication.js
export default ({ app, redirect }) => {
    const auth_token = app.$cookies.get('auth_token')
    if(auth_token == '' || auth_token == null){
        redirect('/login')
    }else{
        app.$axios.get(`/userCoins/getMerchantLists?limit=10&offset=1`,null,{
            headers: app.$cookies.get('auth_token')
          }).then((res)=>{
            if(res.data.status === 'Please login first'){
                redirect('/login')
            }
        })
    }
  }

What is Expected? I want to redirect to login page when the condition is met.

What is actually happening? It gives me an ERROR Cannot set headers after they are sent to the client

https://nuxtjs.org/docs/2.x/components-glossary/pages-middleware/

Edit: I call the middleware via

<script>
export default {
 layout: 'mainLayout',
  middleware: 'authentication', //authentication.js
  data(){
    return{
      merchants:[],
      merchant_id:''
    }
  },

1 answer

  • answered 2021-03-03 02:25 Yaser

    I can't tell based on just the code you have posted, but at first glance it seems like you're missing the return:

    export default ({ app, redirect }) => {
        const auth_token = app.$cookies.get('auth_token')
        if(auth_token == '' || auth_token == null){
            return redirect('/login')
        }else{
            app.$axios.get(`/userCoins/getMerchantLists?limit=10&offset=1`,null,{
                headers: app.$cookies.get('auth_token')
              }).then((res)=>{
                if(res.data.status === 'Please login first'){
                    return redirect('/login')
                }
            })
        }
      }