To start a new application, in order NOT to encounter CORS issue in dev mode, it's always crucial to handle api proxy setup if you need another third party backend service as source.
Here is a quick guideline for beginners to setup.
There are two possible flows.
User enters a page and fetch api related with third party server in either CSR or SSR.
Nuxt Page
– Fetch api through useFetch or $fetch directly – Nitro Server API Proxy Route
–> Backend service
User enters a server only route and the route requires some API response from third party server.
Server Route
– Fetch api through $fetch directly –> Nitro Server API Proxy Route
–> Backend service
Here are simples example for developers to understand the condition of backend service and api entrypoint.
The domain of backend service, it'll change by environment.
.env
.env.production
This variable will be referred as useRuntimeConfig().public.apiBaseUrl
in whole nuxt project.
The api endpoint to serve response. Imagine that calling http://localhost:3005/hello or https://ec-bot-web.line-apps-beta.com/hello
will response a simple JSON.
{api-base-url}/hello
To fetch api, no matter it comes from nuxt page or server route, the path will be like /api/**
so it can be defined as api proxy route pattern later.
Here are two simple examples to fetch api from nuxt pages.
I. Fetch api through useFetch composable.
II. Fetch api through useAsyncData ($fetch) composable.
Here is an example to fetch backend service api in server route. User will get hello world
string by typing URL {your-nitro-host}/hello-world
.
Add a proxy api endpoint in nitro server to handle CORS issue. It will replace /api/**
with /**
and add proxyUrl at the beginning. For example: /api/hello
will be transformed to http://localhost:3005/hello and proxy the request.
That's it! Now you can feel free to request third party backend service api in your application.
It's recommend to use proxyRequest instead of devServer if you need to proxy request in both client and server side because devServer will NOT proxy request in nitro server itself. Which means request from nitro server to nitro server won't trigger a proxy that case. Besides, the api flow will be precise and easy to trace from either CSR or SSR.
Work
Nuxt3
Nitro Server
proxyRequest