nuxt / nuxt

The Intuitive Vue Framework.
https://nuxt.com
MIT License
53.13k stars 4.88k forks source link

How to fix nuxt redirect to homepage on hard refresh and direct access to any page #6824

Closed yamenshahin closed 4 years ago

yamenshahin commented 4 years ago

Version

v2.9.1

Reproduction link

http://manvanstage.com.s3-website.eu-west-2.amazonaws.com/

Steps to reproduce

Navigation via links work perfectly, but if you tried to access any page directly or refresh any page it will redirect you to home page.

What is expected ?

Access any page directly or refresh any page should not redirect to homepage

What is actually happening?

Access any page directly or refresh any page redirect you to home page.

Additional comments?

Here is the website config nuxt.config.js


    export default {
  mode: 'universal',
  /*
   ** Headers of the page
   */
  head: {
    title: 'x',
    htmlAttrs: {
      lang: 'en'
    },
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      {
        hid: 'description',
        name: 'description',
        content: 'x'
      },
      {
        hid: 'keywords',
        name: 'keywords',
        content: 'x'
      }
    ],
    script: [
      { src: 'https://js.stripe.com/v3/' }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
      { rel: 'stylesheet', href: 'https://fonts.googleapis.com/css?family=Roboto+Condensed&display=swap' }
    ]
  },

  /*
   ** Customize the progress-bar color
   */
  loading: { color: '#fff' },
  /*
   ** Global CSS
   */
  css: [
    // You need a specific loader for CSS files
    // https://github.com/mariomka/vue-datetime
    '~node_modules/vue-datetime/dist/vue-datetime.css',
    // Main CSS file in the project
    '@/assets/css/main.css',
    // https://fullcalendar.io/docs/vue
    '@fullcalendar/core/main.css',
    '@fullcalendar/daygrid/main.css',
  ],
  /*
   ** Plugins to load before mounting the App
   */
  plugins: [
    // The plugin is auth related which change user status to logged
    '~plugins/mixins/user.js',
    // The plugin is google map place object related which get collectionPlace and deliveryPlace objects
    '~plugins/mixins/places.js',
    // The plugin used for getting search for driver meta before searching
    '~plugins/mixins/search.js',
    // DateTimePicker
    { ssr: false, src: '~plugins/datetime.js'  },
    // The plugin used to store and getting final search result
    '~plugins/mixins/search-result.js',
    // The plugin used to store and getting customer jobs
    '~plugins/mixins/customer-jobs.js',
    // The plugin used to store and getting driver jobs
    '~plugins/mixins/driver-jobs.js',
    // The plugin is google map place object related which get Driver Place object
    '~plugins/mixins/driver-place.js',
    // Google Map API https://github.com/xkjyeah/vue-google-maps
    // https://developers.google.com/maps/solutions/store-locator/clothing-store-locator
    { ssr: false, src: '~plugins/google-maps.js'  },
    // Persist and rehydrate your Vuex state between page reloads.
    // https://github.com/robinvdvleuten/vuex-persistedstate
    { ssr: false, src: '~plugins/localStorage.js'  },
    // The plugin is contains google map common tasks
    '~plugins/mixins/google-map-common-tasks.js',
    // The plugin is contains math common tasks
    '~plugins/mixins/math-common-tasks.js',
    // The plugin is for formating or filters
    '~plugins/mixins/filters.js',
    // The plugin is for store current checkout job
    '~plugins/mixins/checkout.js',
    // The plugin Vue MQ (MediaQuery)
    // https://github.com/AlexandreBonaventure/vue-mq
    '~plugins/media-query.js',
    // https://github.com/cretueusebiu/vform
    '~plugins/vform.js',
    //https://github.com/fullcalendar/fullcalendar-vue/issues/5
    { ssr: false, src: '~/plugins/full-calendar'  },
    // Get all places (id, lat, lng) used for area we cover
    '~plugins/mixins/area.js',
    // Star Rating Component for Vue 2.x
    // https://github.com/craigh411/vue-star-rating
    '~plugins/star-vote.js',
    // Home HTML
    '~plugins/mixins/home-html.js',
    // Lazy load
    //https://github.com/Akryum/vue-observe-visibility
    //https://vueschool.io/articles/vuejs-tutorials/async-vuejs-components/
    '~plugins/lazyload.js',
  ],
  /*
   ** Nuxt.js dev-modules
   */
  buildModules: [
    // Doc: https://github.com/nuxt-community/eslint-module
    '@nuxtjs/eslint-module'
  ],
  /*
   ** Nuxt.js modules
   */
  modules: [
    // Doc: https://bootstrap-vue.js.org/docs/
    'bootstrap-vue/nuxt',
    // Doc: https://axios.nuxtjs.org/usage
    '@nuxtjs/axios',
    '@nuxtjs/auth',
    // Load .env
    '@nuxtjs/dotenv',
    // Font awesome
    ['nuxt-fontawesome', {
      component: 'fa',
      imports: [
        {
          set: '@fortawesome/free-solid-svg-icons',
          icons: ['fas']
        },
        {
          set: '@fortawesome/free-brands-svg-icons',
          icons: ['fab']
        },
      ]
    }],

    '@nuxtjs/sitemap'

  ],
  /**
   * .env
   */
  env: {
    VUE_APP_GOOGLE_MAPS_API_KEY: process.env.VUE_APP_GOOGLE_MAPS_API_KEY,
    stripe_key: process.env.NODE_ENV !== 'production' ? 'pk_test_123' : 'pk_test_123',
    google_tag_on:false, 
  },
  /*
   ** Axios module configuration
   ** See https://axios.nuxtjs.org/options
   */
  axios: {
    baseURL: process.env.NODE_ENV !== 'production' ? 'http://127.0.0.1:8000/api/' : 'http://hellovans-env.rqeysdn8mi.eu-west-2.elasticbeanstalk.com/api/',
    //credentials: false
    //proxy: true,
    //https: true
  },
  proxy: {
    '/api/': {
      target: process.env.NODE_ENV !== 'production' ? 'http://127.0.0.1:8000/' : 'http://hellovans-env.rqeysdn8mi.eu-west-2.elasticbeanstalk.com/'
    }
  }, 
  auth: {
    //plugins: ['~/plugins/auth.js'],
    strategies: {
      local: {
        endpoints: {
          login: { url: 'login', method: 'post', propertyName: 'meta.token' },
          logout: { url: 'logout', method: 'post' },
          user: { url: 'user', method: 'get', propertyName: 'data' }
        },
      }
    },

  },
  /*
   ** Build configuration
   */
  build: {
    /*
     ** You can extend webpack config here
     */
    //analyze: true,
    extend(config, ctx) {
      // Run ESLint on save
      if (ctx.isDev && ctx.isClient) {
        config.module.rules.push({
          enforce: "pre",
          test: /\.(js|vue)$/,
          loader: "eslint-loader",
          exclude: /(node_modules)/,
          options: {
            fix: true
          }
        })
      }
    }
  },
  server: {
    port: 3001, // default: 3000
    host: 'localhost' // default: localhost
  }
}
aldarund commented 4 years ago

Nothing is redirected on your site. http://manvanstage.com.s3-website.eu-west-2.amazonaws.com/area-we-cover

refresh and it stays there nothing redirected

yamenshahin commented 4 years ago

Apparently this happens only if you are not logged in before, so maybe it's something related to nuxt/auth and cleared site data (storage, cache etc..)

Nothing is redirected on your site. http://manvanstage.com.s3-website.eu-west-2.amazonaws.com/area-we-cover

refresh and it stays there nothing redirected

aldarund commented 4 years ago

No idea what u mean by not loged in before. I didnt login at all. So anyway its seems like its soem of your code or configuration. Create a minimal reproduction with your problem, otherwise its nearly impossible to help

truesteps commented 4 years ago

Yes, this issue seems to pop up in nuxt/auth, I cannot figure out what's wrong for the life of me, but it seems that the login doesn't persist on the server side, so you're just logged out there, but as soon as you get to client side, you're suddenly magically logged in and I have no idea how to work around this bug, it's been killing me for the last 3 days... It happens when I just log in with local scheme and I hit refresh, as long as I don't reload manually, it works fine.

giovannimanzoni commented 4 years ago

hello @truesteps , hahaha, same problem like me, same orrible situation.. but... I think it is the right thing that must happen, After one week that i understand better nuxt/auth, I understand that when you refresh manualy, you obviusly do not send header with any token, so logout...

stale[bot] commented 4 years ago

Thanks for your contribution to Nuxt.js! This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. If you would like this issue to remain open:

  1. Verify that you can still reproduce the issue in the latest version of nuxt-edge
  2. Comment the steps to reproduce it

Issues that are labeled as pending will not be automatically marked as stale.

kamilcglr commented 4 years ago

Hello everyone, did you find any solution to this ? It seems I have the same issue :

I configured my server with nginx as a reverse proxy for a Nuxt/Express SSR application. For the moment I have a login page, and a home page.

I can connect and disconnect without any problem.

However, when I'm connected and I refresh the page, the loading time is very long.

I don't know if this is due to Nginx configuration or the authentication API or redirection.

I've noticed that it also happens when I type my url myself in the address bar.

nomikz commented 3 years ago

I confirm this issue. On dev environment, when I do npm run dev, I have this issue. I login and when I refresh, it redirects me as if I am not logged in.

But when It is productions environment npm run build && npm run start, It works fine. It doesn't redirect. I really don't like how nuxt auth works. Documentation, to say the least, leaves a lot to be desired.

Didza commented 2 years ago

Nuxt auth will be the final nail in the coffin for me to start using react on this current project.

yamenshahin commented 2 years ago

Nuxt auth will be the final nail in the coffin for me to start using react on this current project.

Agree

truesteps commented 2 years ago

Nuxt auth will be the final nail in the coffin for me to start using react on this current project.

Agree

any time I had any issue with nuxt auth, it ended up being a backend issue. I recommend you guys adding a global interceptor to axios, overwrite all the callbacks and log them on both client/server. I ran into an issue, where the issued SSL certificate was faulty so nuxt auth call didn't go through on nuxt server or just backend cookie handling plain misconfigured since I use laravel + sanctum as authentication nowadays. Basically I was cursing nuxt auth but it was never an issue of this library.

Guys you gotta keep in mind, that theres two sides to this, one that happens on the server that does SSR and client side in the browser. If one fails the other is attempted but it can result it different behaviour like these redirects. It's just separate issues while implementing ANY login using SSR and no ssr

CharlesBilbo commented 2 years ago

@nomikz Your issue could be because when running nextServerInit it needs to use the internal URL so if it's in a docker image it needs to reference the internal docker URL https://axios.nuxtjs.org/options/

yiyasha15 commented 2 years ago

Did anyone find a solution to this? I'm facing the same issue with a similar code structure.

For me, if i'm not logged in -> protected page -> page refresh -> stays on the same page. but if i'm logged in -> protected page -> page refresh -> goes to the home page.

my middleware code

export default function({store, redirect }) {
  const isAuthenticated = store.state.auth.loggedIn ? true : false
  if (!isAuthenticated) {
    redirect("/login")
  }
  else{
    console.log("stay on the same page");
  }
}

Please suggest any solution I could use. ~Thanks.

Didza commented 2 years ago

If you have server side rendering on you will need to validate you cookie exists or else redirect. Then only check is authenticated on the client side. N.B using cookie-universal-nuxt package for the cookies The idea: ` // server side check for token const user = await app.$cookies.get('auth_token') if (!user) { redirect('/') }

// Then client side if (process.client && $auth.loggedIn) { // can do checks if token needs to be refreshed or expired here } else if (process.client) { redirect('/') }

`

Onyoursix commented 11 months ago

Is there any update on this? I believe I'm running into the same/similar issue. This issue seems to have come out of nowhere in dev mode. Started up my dev environment yesterday and now reloading any page redirects me to localhost:3000, no errors, nothing. This almost seems like some weird caching issue however wiping my cache doesn't seem to fix the issue. Issue happens in Chrome & Firefox, however, incognito Firefox does not reproduce the issue (still have the issue with Chrome incognito).

I know this thread is old, but curious if anyone has a suggestion/solution. I'm pulling my hair out over this.

edit one strange thing I notice is if I go to localhost:3000/mypage it then redirects me to localhost:3000, but if I do localhost:3000/mypage?c=testquery it redirects me to localhost:3000?c=testquery


yiyasha15 commented 11 months ago

@Onyoursix are you using nuxt-auth module?

For me it resolved when I updated to the new version of nuxt-auth. I'm not sure why but the previous version was causing this error for me.

hussainalihussain commented 11 months ago

Is there any update on this? I believe I'm running into the same/similar issue. This issue seems to have come out of nowhere in dev mode. Started up my dev environment yesterday and now reloading any page redirects me to localhost:3000, no errors, nothing. This almost seems like some weird caching issue however wiping my cache doesn't seem to fix the issue. Issue happens in Chrome & Firefox, however, incognito Firefox does not reproduce the issue (still have the issue with Chrome incognito).

I know this thread is old, but curious if anyone has a suggestion/solution. I'm pulling my hair out over this.

edit one strange thing I notice is if I go to localhost:3000/mypage it then redirects me to localhost:3000, but if I do localhost:3000/mypage?c=testquery it redirects me to localhost:3000?c=testquery

  • Operating System: Linux
  • Node Version: v20.1.0
  • Nuxt Version: 3.6.5
  • Nitro Version: 2.5.2
  • Package Manager: npm@9.6.4
  • Builder: vite
  • User Config: imports, modules, pwa, css, build, nitro
  • Runtime Modules: @pinia/nuxt@0.4.11, @vite-pwa/nuxt@0.1.0, ()
  • Build Modules: -

Yes I have the same problem, only work in firefox incognito mode (I don't have nuxt-auth too)

Onyoursix commented 11 months ago

@Onyoursix are you using nuxt-auth module?

For me it resolved when I updated to the new version of nuxt-auth. I'm not sure why but the previous version was causing this error for me.

I am not using the nuxt-auth, I actually believe this is an issue with vite-pwa/nuxt plugin. After disabling the pwa plugin the issue seems to go away. https://github.com/vite-pwa/nuxt/issues/56

buditanrim commented 8 months ago

Hi, I face the same issue. Whenever I go to /privacy or another page, it will redirect to the front page. Has anyone found a good solution for this?

manniL commented 8 months ago

Hi, I face the same issue. Whenever I go to /privacy or another page, it will redirect to the front page. Has anyone found a good solution for this?

Still not a nuxt issue. :D You might use the supabase module on any other that does that by default ☺️