Mastodon hachyterm.io

I’m currently working on a Vite React application with a Nest.js backend.

The React app runs on localhost:3000 and the backend on localhost:4000.
When I query the backend from React, I get a CORS error.

After unsucessfully trying to enable cors for local development, I’ve gone back to using a Proxy setting in my vite config.
This behavior is similar to Create React App’s proxy setting.

In the viteconfig.ts file, add the following to your configuration:

// https://vitejs.dev/config/
export default defineConfig({
  server: {
    port: 3000,
    proxy: {
      '/api': {
        target: 'http://localhost:4000',
        rewrite: (path) => path.replace(/^\/api/, ''),
      },
    },
  },
})

The setting re-routes all traffic on localhost:3000/api to the backend url localhost:4000 and then removes the /api suffix.

In your application, target your backend API via localhost:3000/api instead of the “real” URL localhost:4000.

For example:

import { ApolloClient, InMemoryCache } from '@apollo/client'
import { API_URL } from './urls'

export const client = new ApolloClient({
  uri: `localhost:3000/api/graphql`,
  credentials: 'include',
  cache: new InMemoryCache(),
})

Underneath the hood, the proxy will route to localhost:4000/graphql. And you won’t have CORS errors.
Neat!

Further Reading