W
Wasp3w ago
Juan

Setting up Cors in 0.16.0

I had cors middleware config working in 0.14.0. No longer working after upgrading to 0.16.0. How do I set up cors config to work with lates WASP version?
12 Replies
kapa.ai
kapa.ai3w ago
Hi @Juan. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- I'll help you set up CORS in Wasp 0.16.0. It seems there might have been some changes in how CORS is configured between versions. In Wasp, CORS is included by default in the global middleware, but you might need to customize it for your specific needs. Here are the approaches you can take: 1. Customize Global Middleware This is the recommended approach if you want to modify CORS settings for all operations and APIs:
// main.wasp
app todoApp {
// ...
server: {
middlewareConfigFn: import { serverMiddlewareFn } from "@src/serverSetup"
},
}

// src/serverSetup.js
import cors from 'cors'
import { config } from 'wasp/server'

export const serverMiddlewareFn = (middlewareConfig) => {
// Example of adding extra domains to CORS
middlewareConfig.set('cors', cors({
origin: [config.frontendUrl, '<https://example1.com',> '<https://example2.com']>
}))
return middlewareConfig
}
// main.wasp
app todoApp {
// ...
server: {
middlewareConfigFn: import { serverMiddlewareFn } from "@src/serverSetup"
},
}

// src/serverSetup.js
import cors from 'cors'
import { config } from 'wasp/server'

export const serverMiddlewareFn = (middlewareConfig) => {
// Example of adding extra domains to CORS
middlewareConfig.set('cors', cors({
origin: [config.frontendUrl, '<https://example1.com',> '<https://example2.com']>
}))
return middlewareConfig
}
This will apply your CORS configuration globally Configuring Middleware. 2. Use apiNamespace for API-specific CORS If you're experiencing CORS issues with specific API endpoints, you should use apiNamespace to ensure CORS is properly set up for both the main HTTP methods and the OPTIONS preflight requests:
// main.wasp
apiNamespace myApi {
middlewareConfigFn: import { myApiMiddlewareFn } from "@src/apis",
path: "/api"
}

// src/apis.js
export const myApiMiddlewareFn = (config) => {
// You can customize CORS here if needed
return config;
}
// main.wasp
apiNamespace myApi {
middlewareConfigFn: import { myApiMiddlewareFn } from "@src/apis",
path: "/api"
}

// src/apis.js
export const myApiMiddlewareFn = (config) => {
// You can customize CORS here if needed
return config;
}
This approach is particularly important because one common issue is that CORS needs to be configured not just for your main HTTP methods (GET, POST, etc.) but also for the OPTIONS preflight requests Custom HTTP API Endpoints. Common Issues If you're still experiencing CORS errors, it might be due to: 1. Not handling OPTIONS preflight requests correctly 2. Authorization headers causing CORS issues (as mentioned in a GitHub issue) 3. The order in which middleware is registered The Wasp team has identified this as a confusing area that needs improvement, as noted in GitHub Issue #1303. If you continue to have issues, please provide more details about your specific setup and the exact CORS error you're seeing. Let me know if this helps or if you need further assistance! ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @Juan, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
Filip
Filip3w ago
Hey @Juan, why do you think its a CORS problem? I'm asking because this seems unlikely since we haven't changed anything. Which error are you getting? FWIW, users often misdiagnose various server issues as CORS issues. If I was a betting man, I'd bet on that: https://discord.com/channels/686873244791210014/1323006880154517606/1326103930786152459
Juan
JuanOP2w ago
Not sure what the issue, but after multiple updates to my serverConfig (which sometimes works with localhost) file I keep getting the following error when I deploy: /login:1 Access to XMLHttpRequest at 'https://chordamigo-server.apps.chordamigo.com/auth/me' from origin 'https://chordamigo-client.apps.chordamigo.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values 'https://chordamigo-client.apps.chordamigo.com, https://chordamigo-server.apps.chordamigo.com', but only one is allowed. That's just one variation. I'll come back to it tomorrow.
Filip
Filip2w ago
Oh, so it really is CORS. Check your WASP_WEB_CLIENT_URL env var. Looks like it possibly has multiple values But that sounds far fetched. Hm... @miho any other ideas. You only need to read this message: https://discord.com/channels/686873244791210014/1351647113846456370/1352021521958436957
miho
miho2w ago
@Filip that's a good guess, @Juan what's the value of your WASP_WEB_CLIENT_URL env var in production? Could you share your latest server.setupFn code? This is a gist I share often, let me know if this works for you: https://gist.github.com/infomiho/5ca98e5e2161df4ea78f76fc858d3ca2
Gist
Multiple domains for CORS - custom global middleware in Wasp 0.12+
Multiple domains for CORS - custom global middleware in Wasp 0.12+ - main.wasp
miho
miho2w ago
One extra insight from LLMs: don't use trailing slashes when specifying your domain https://chordamigo-client.apps.chordamigo.com/ -> https://chordamigo-client.apps.chordamigo.com
Juan
JuanOP2w ago
My current config: main.wasp
server: {
middlewareConfigFn: import { getGlobalMiddleware } from "@src/server/serverConfig",
},
server: {
middlewareConfigFn: import { getGlobalMiddleware } from "@src/server/serverConfig",
},
serverConfig.ts
import cors from "cors";
import { MiddlewareConfigFn } from "wasp/server";


export const getGlobalMiddleware: MiddlewareConfigFn = (config) => {
const isDevelopment = process.env.NODE_ENV === "development";
console.log("isDevelopment", isDevelopment);
const clientUrl = process.env.WASP_WEB_CLIENT_URL ?? "http://localhost:3000";
const serverUrl = process.env.WASP_SERVER_URL ?? "http://localhost:3001";

const origin = isDevelopment ? "*" : [clientUrl, serverUrl];


config.delete("cors");
config.set(
"cors",
cors({
origin,
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH'],
allowedHeaders: [
'Content-Type',
'Authorization',
'X-Requested-With',
'Accept',
'Origin'
],
exposedHeaders: ['Access-Control-Allow-Origin'],
preflightContinue: false,
optionsSuccessStatus: 204
})
);


return config;
};
import cors from "cors";
import { MiddlewareConfigFn } from "wasp/server";


export const getGlobalMiddleware: MiddlewareConfigFn = (config) => {
const isDevelopment = process.env.NODE_ENV === "development";
console.log("isDevelopment", isDevelopment);
const clientUrl = process.env.WASP_WEB_CLIENT_URL ?? "http://localhost:3000";
const serverUrl = process.env.WASP_SERVER_URL ?? "http://localhost:3001";

const origin = isDevelopment ? "*" : [clientUrl, serverUrl];


config.delete("cors");
config.set(
"cors",
cors({
origin,
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH'],
allowedHeaders: [
'Content-Type',
'Authorization',
'X-Requested-With',
'Accept',
'Origin'
],
exposedHeaders: ['Access-Control-Allow-Origin'],
preflightContinue: false,
optionsSuccessStatus: 204
})
);


return config;
};
Juan
JuanOP2w ago
Server environment variables in CapRover
No description
Juan
JuanOP2w ago
This setup worked with 0.14. I did allow all origins though when deployed. Now I'm just trying to get it to work with more restrictions with latest wasp version.
miho
miho2w ago
Hm, I'll test out the exact setup later and let you know what I find
Juan
JuanOP2w ago
Thank you. I think I found something. Because the db schema changed when updating to the latest wasp version. I may have broken my database when re-doing the wasp db migrate-dev to update the prod tables. Going to look into this and might just delete the db and recreate it. I think you're right in that some underlying issue was causing the Cors errors even though it wasn't a true Cors error. Is there documentation on doing db migrations to production environments? Appreciate your assistance.
miho
miho2w ago
Check the "Debugging failed migrations" section here: https://wasp.sh/docs/deployment/database If you need some help or have any questions. ping me
Database | Wasp
In this section, we'll discuss what happens with the database when your app goes live. When you develop your app locally, you probably use a local dev database (started with wasp start db or some other way). However, when it's time to deploy your app, you'll need to set up a production database.

Did you find this page helpful?