Hamzeh
Hamzeh

Reputation: 311

Nuxt js: how to use proxy in laravel sanctum?

Nuxt js NOTE: It is highly recommended to use proxy to avoid CORS and same-site policy issues.

I couldn't understand the use of "target" and "pathRewrite " in the proxy.

who can describe them?

if my backend(laravel) URL be localhost:8000 and my frontend(Nuxt) URL be localhost:3000 then how should I config it?

image from auth.nuxtjs.org

Upvotes: 2

Views: 1964

Answers (1)

Eliyas Hossain
Eliyas Hossain

Reputation: 620

You may use Axios proxy in NuxtJS like this:

export default {
  axios: {
    credentials: true,
    proxy: true,
    debug: process.env.NODE_ENV !== 'production',
  },
  proxy: {
    '/api/': process.env.API_URL,
  },
  auth: {
    redirect: {
      login: '/auth/login',
      logout: '/auth/login',
      callback: '/auth/login',
      home: '/feed',
    },
    strategies: {
      laravelSanctum: {
        provider: 'laravel/sanctum',
        url: 'api', // note the URL here.
        endpoints: {
          login: {
            url: '/auth/login',
          },
          logout: {
            url: '/auth/logout',
          },
          user: {
            url: '/auth/me',
          },
        },
      },
    }
  }
}

I couldn't understand the use of "target" and "pathRewrite " in the proxy.

Let's say your API_URL is localhost:8000.

If you write proxy config like this:

proxy: {
  '/api': process.env.API_URL,
},

It will add /api at the end of the URL. So your API_URL will be localhost:8000/api. Now you may call API request with Axios like this:

this.$axios.$get('api/me');

In the behind, it will call to this URL: localhost:8000/api/me.

If you write your proxy config like this:

proxy: {
  '/api': {
    target: process.env.API_URL,
    pathRewrite: { '^/api': '/' }
  }
},

It will remove /api from the end of the URL. So your API_URL will be localhost:8000.

Now you may call API request with Axios like this:

this.$axios.$get('api/me');

In the behind, it will call to this URL: localhost:8000/me.

Enjoy :)

Upvotes: 4

Related Questions