CORS ERROR

Having some trouble finding how to allow custom origins in my wasp app. I make the api call using wasps api in the client to request from an api in the server, same app. I am in local host
15 Replies
kapa.ai
kapa.ai7d ago
Hi @Stefan Vitória. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- To address CORS issues in your Wasp app when making API calls from the client to the server on localhost, you have a few options: 1. Use the default CORS configuration: By default, Wasp configures CORS to allow requests from the frontend URL, which includes localhost during development. This should work out of the box for most local development scenarios. 2. Customize global middleware: If you need more control, you can customize the global middleware to configure CORS. Here's an example:
// main.wasp
app todoApp {
// ...
server: {
setupFn: import setup from "@src/serverSetup",
middlewareConfigFn: import { serverMiddlewareFn } from "@src/serverSetup"
},
}

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

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

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

export const serverMiddlewareFn = (middlewareConfig) => {
middlewareConfig.set('cors', cors({ origin: [config.frontendUrl, '<https://example1.com',> '<https://example2.com']> }))
return middlewareConfig
}
This approach allows you to add custom origins to the CORS configuration Configuring Middleware (https://wasp-lang.dev/docs/advanced/middleware-config#1-customize-global-middleware). 3. Use an apiNamespace: If you're still experiencing issues, especially with OPTION requests, you might need to use an apiNamespace. This is often the most reliable way to configure CORS for custom API endpoints:
// main.wasp
apiNamespace myApi {
middlewareConfigFn: import { myApiMiddleware } from "@src/apis",
path: "/api"
}

// src/apis.js
import cors from 'cors'

export const myApiMiddleware = (middlewareConfig) => {
middlewareConfig.set('cors', cors({ origin: '<http://localhost:3000'> }))
return middlewareConfig
}
// main.wasp
apiNamespace myApi {
middlewareConfigFn: import { myApiMiddleware } from "@src/apis",
path: "/api"
}

// src/apis.js
import cors from 'cors'

export const myApiMiddleware = (middlewareConfig) => {
middlewareConfig.set('cors', cors({ origin: '<http://localhost:3000'> }))
return middlewareConfig
}
This approach ensures that CORS is properly set up for all HTTP methods, including OPTIONS Making Sure CORS Works (https://wasp-lang.dev/docs/advanced/apis#making-sure-cors-works). If you're still encountering issues after trying these approaches, it might be helpful to provide more details about your specific setup and the exact error you're seeing. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @Stefan Vitória, 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?
Stefan Vitória
Stefan VitóriaOP7d ago
this is the erro @kapa.ai Access to XMLHttpRequest at 'http://localhost:3001/api/validateQrCodeScan' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
kapa.ai
kapa.ai7d ago
Let me check the knowledge base for you again. One moment! :books: ---------------------- Based on the error message you're seeing, it appears that the CORS configuration for your Wasp app is not properly set up to allow requests from your client (running on <http://localhost:3000>) to your server (running on <http://localhost:3001>). Let's address this issue using the apiNamespace approach, which is often the most reliable way to configure CORS for custom API endpoints in Wasp. Here's how you can modify your Wasp configuration to resolve this CORS error: 1. In your main.wasp file, add an apiNamespace declaration:
apiNamespace myApi {
middlewareConfigFn: import { myApiMiddleware } from "@src/apis",
path: "/api"
}
apiNamespace myApi {
middlewareConfigFn: import { myApiMiddleware } from "@src/apis",
path: "/api"
}
2. Create or modify the src/apis.js (or src/apis.ts if you're using TypeScript) file:
import cors from 'cors'

export const myApiMiddleware = (middlewareConfig) => {
middlewareConfig.set('cors', cors({
origin: '<http://localhost:3000',>
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization']
}))
return middlewareConfig
}
import cors from 'cors'

export const myApiMiddleware = (middlewareConfig) => {
middlewareConfig.set('cors', cors({
origin: '<http://localhost:3000',>
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization']
}))
return middlewareConfig
}
This configuration explicitly allows requests from <http://localhost:3000,> which is where your client is running. It also specifies the allowed methods and headers. By using this approach, you're ensuring that the CORS middleware is applied correctly to your API routes, including the OPTIONS preflight requests that are causing the error you're seeing. If you're still experiencing issues after implementing this solution, make sure that your API endpoint (/api/validateQrCodeScan) is properly defined in your Wasp configuration and that it falls under the /api path specified in the apiNamespace. For more detailed information on configuring CORS in Wasp, you can refer to the Making Sure CORS Works (https://wasp-lang.dev/docs/advanced/apis#making-sure-cors-works) section in the Wasp documentation. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @Stefan Vitória, 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?
Stefan Vitória
Stefan VitóriaOP7d ago
same error: Access to XMLHttpRequest at 'http://localhost:3001/api/validateQrCodeScan' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. @kapa.ai same error: Access to XMLHttpRequest at 'http://localhost:3001/api/validateQrCodeScan' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
kapa.ai
kapa.ai7d ago
Let me check the knowledge base for you again. One moment! :books: ---------------------- I apologize that you're still experiencing the same CORS error. Let's try a different approach to resolve this issue. Based on the information provided in the knowledge sources, there might be a more specific way to handle CORS in Wasp, especially for custom API endpoints. Let's modify your Wasp configuration as follows: 1. In your main.wasp file, add or modify the server configuration:
app yourAppName {
// ... other app configurations ...

server: {
setupFn: import setup from "@src/serverSetup",
middlewareConfigFn: import { serverMiddlewareFn } from "@src/serverSetup"
},
}
app yourAppName {
// ... other app configurations ...

server: {
setupFn: import setup from "@src/serverSetup",
middlewareConfigFn: import { serverMiddlewareFn } from "@src/serverSetup"
},
}
2. Create or modify the src/serverSetup.js (or src/serverSetup.ts for TypeScript) file:
import cors from 'cors'
import { config } from 'wasp/server'

export const serverMiddlewareFn = (middlewareConfig) => {
middlewareConfig.set('cors', cors({
origin: [config.frontendUrl, '<http://localhost:3000'],>
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization']
}))
return middlewareConfig
}
import cors from 'cors'
import { config } from 'wasp/server'

export const serverMiddlewareFn = (middlewareConfig) => {
middlewareConfig.set('cors', cors({
origin: [config.frontendUrl, '<http://localhost:3000'],>
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization']
}))
return middlewareConfig
}
This configuration explicitly allows requests from both the default frontend URL (which Wasp sets automatically) and 'http://localhost:3000'. It also specifies the allowed methods and headers. If you're still encountering issues after implementing this solution, there are a few more things you can try: 1. Make sure you've restarted your Wasp server after making these changes. 2. Double-check that your API endpoint (/api/validateQrCodeScan) is correctly defined in your Wasp configuration. 3. If possible, try using the api object provided by Wasp for making requests from the client side, as it should handle CORS automatically:
import api from '@wasp/api'
// Use this instead of direct fetch or XMLHttpRequest
const response = await api.get('/api/validateQrCodeScan')
import api from '@wasp/api'
// Use this instead of direct fetch or XMLHttpRequest
const response = await api.get('/api/validateQrCodeScan')
If none of these solutions work, it's possible that there might be a more complex issue at play. In that case, you might want to consider opening an issue on the Wasp GitHub repository (https://github.com/wasp-lang/wasp/issues) or seeking help on the Wasp Discord channel (https://discord.com/invite/rzdnErX) for more personalized assistance. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @Stefan Vitória, 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?
Stefan Vitória
Stefan VitóriaOP7d ago
this is how i am making the request: const response = await api.post(http://localhost:3001/api/validateQrCodeScan, { headers: { "Content-Type": "application/json", }, body: JSON.stringify({ email, gymSlug: slug }), }); @kapa.ai @kapa.ai this is how i am making the request: const response = await api.post(http://localhost:3001/api/validateQrCodeScan, { headers: { "Content-Type": "application/json", }, body: JSON.stringify({ email, gymSlug: slug }), });
kapa.ai
kapa.ai7d ago
Let me check the knowledge base for you again. One moment! :books: ---------------------- Thank you for providing the code snippet of how you're making the request. I can see a potential issue with your current approach. Let me explain and provide a correction: The way you're using the api.post method is incorrect. When using Wasp's api object, you don't need to specify the full URL including the host and port. Wasp's api object is designed to handle the base URL for you. Here's how you should modify your request:
const response = await api.post("/api/validateQrCodeScan", {
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ email, gymSlug: slug }),
});
const response = await api.post("/api/validateQrCodeScan", {
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ email, gymSlug: slug }),
});
By removing <http://localhost:3001> from the URL, you're allowing Wasp to handle the base URL configuration internally. This approach should work correctly with Wasp's built-in CORS configuration. If you're still experiencing CORS issues after making this change, it's possible that there might be a configuration problem on the server side. In that case, you might want to double-check your server setup, particularly the CORS configuration in your main.wasp file and any related server setup files. For more information on using Wasp's api object, you can refer to the Using the API from the Client (https://wasp-lang.dev/docs/advanced/apis#making-sure-cors-works) section in the Wasp documentation. If the problem persists after making this change, please let me know, and we can explore other potential solutions. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @Stefan Vitória, 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?
Stefan Vitória
Stefan VitóriaOP7d ago
@kapa.ai it still doesnt work. But i test it using insomnia it works with no problem
kapa.ai
kapa.ai7d ago
Let me check the knowledge base for you again. One moment! :books: ---------------------- I understand that you're still experiencing issues with the API call from your Wasp client, but it works when you test it using Insomnia. This suggests that the problem might be related to how the request is being made from the client side rather than a server-side CORS configuration issue. Let's explore a few potential solutions: 1. Double-check your API definition: Make sure your API is correctly defined in your main.wasp file. It should look something like this:
api validateQrCodeScan {
httpRoute: (POST, "/api/validateQrCodeScan"),
fn: import { validateQrCodeScan } from "@server/apis/qrCode.js",
auth: false // or true if authentication is required
}
api validateQrCodeScan {
httpRoute: (POST, "/api/validateQrCodeScan"),
fn: import { validateQrCodeScan } from "@server/apis/qrCode.js",
auth: false // or true if authentication is required
}
2. Try using fetch instead of api.post: While Wasp's api object should work, let's try using fetch directly to see if it resolves the issue:
const response = await fetch("<http://localhost:3001/api/validateQrCodeScan",> {
method: 'POST',
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ email, gymSlug: slug }),
});
const response = await fetch("<http://localhost:3001/api/validateQrCodeScan",> {
method: 'POST',
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ email, gymSlug: slug }),
});
3. Check for any client-side errors: Open your browser's developer tools and check the Console tab for any JavaScript errors that might be preventing the request from being made correctly. 4. Verify the server is running: Ensure that your Wasp server is running on port 3001 as expected. 5. Consider using apiNamespace: If none of the above solutions work, you might need to explicitly configure CORS using an apiNamespace. Add this to your main.wasp file:
apiNamespace myApi {
middlewareConfigFn: import { myApiMiddleware } from "@server/middleware.js",
path: "/api"
}
apiNamespace myApi {
middlewareConfigFn: import { myApiMiddleware } from "@server/middleware.js",
path: "/api"
}
Then in your server/middleware.js file:
import cors from 'cors'
export const myApiMiddleware = (middlewareConfig) => {
middlewareConfig.set('cors', cors({
origin: '<http://localhost:3000',>
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization']
}))
return middlewareConfig
}
import cors from 'cors'
export const myApiMiddleware = (middlewareConfig) => {
middlewareConfig.set('cors', cors({
origin: '<http://localhost:3000',>
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization']
}))
return middlewareConfig
}
If you're still encountering issues after trying these solutions, it might be helpful to open an issue on the Wasp GitHub repository (https://github.com/wasp-lang/wasp/issues) with more details about your setup, including relevant parts of your main.wasp file and client-side code. The Wasp team might be able to provide more specific guidance based on your particular configuration. Improve our CORS + API story (https://github.com/wasp-lang/wasp/issues/1303) suggests that there are ongoing efforts to improve CORS handling in Wasp, so this might be a known issue that the team is working on resolving. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @Stefan Vitória, 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?
Stefan Vitória
Stefan VitóriaOP7d ago
same thing using fecth @kapa.ai same thing using fecth
kapa.ai
kapa.ai7d ago
Let me check the knowledge base for you again. One moment! :books: ---------------------- I apologize that you're still experiencing issues even when using fetch. Since the problem persists with both Wasp's api object and the standard fetch method, it suggests that there might be a more fundamental issue with the CORS configuration on your Wasp server. Let's try a more comprehensive approach to resolve this CORS issue: 1. First, let's modify your main.wasp file to include a global CORS configuration:
app yourAppName {
// ... other app configurations ...

server: {
setupFn: import setup from "@src/serverSetup",
middlewareConfigFn: import { serverMiddlewareFn } from "@src/serverSetup"
},
}
app yourAppName {
// ... other app configurations ...

server: {
setupFn: import setup from "@src/serverSetup",
middlewareConfigFn: import { serverMiddlewareFn } from "@src/serverSetup"
},
}
2. Now, create or modify the src/serverSetup.js (or src/serverSetup.ts for TypeScript) file:
import cors from 'cors'
import { config } from 'wasp/server'

export const serverMiddlewareFn = (middlewareConfig) => {
middlewareConfig.set('cors', cors({
origin: [config.frontendUrl, '<http://localhost:3000'],>
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization'],
credentials: true
}))
return middlewareConfig
}

export const setup = (app) => {
// Any additional setup you might need
}
import cors from 'cors'
import { config } from 'wasp/server'

export const serverMiddlewareFn = (middlewareConfig) => {
middlewareConfig.set('cors', cors({
origin: [config.frontendUrl, '<http://localhost:3000'],>
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization'],
credentials: true
}))
return middlewareConfig
}

export const setup = (app) => {
// Any additional setup you might need
}
This configuration explicitly allows requests from both the default frontend URL and 'http://localhost:3000', and includes all necessary HTTP methods and headers. 3. After making these changes, make sure to restart your Wasp server completely. 4. If you're still encountering issues, you might need to modify your client-side fetch call to include credentials:
const response = await fetch("<http://localhost:3001/api/validateQrCodeScan",> {
method: 'POST',
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ email, gymSlug: slug }),
credentials: 'include'
});
const response = await fetch("<http://localhost:3001/api/validateQrCodeScan",> {
method: 'POST',
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ email, gymSlug: slug }),
credentials: 'include'
});
If none of these solutions work, it's possible that there might be a more complex issue at play. The Wasp team is aware of some challenges with CORS configuration, as evidenced by the open issue Improve our CORS + API story (https://github.com/wasp-lang/wasp/issues/1303). Given the persistent nature of this problem, I would strongly recommend reaching out to the Wasp team directly. You can do this by: 1. Opening an issue on the Wasp GitHub repository (https://github.com/wasp-lang/wasp/issues), providing details about your setup and the steps you've taken so far. 2. Joining the Wasp Discord channel (https://discord.com/invite/rzdnErX) and asking for help in the appropriate support channel. The Wasp team or community members might be able to provide more specific guidance based on your particular configuration and the current state of CORS handling in Wasp. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @Stefan Vitória, 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
Filip6d ago
Hey @Stefan Vitória, I see you're talking with the bot. If you end up needing human help, please summariese the current situation in a message and tag me 🙂
Stefan Vitória
Stefan VitóriaOP6d ago
Hello @Filip i believe i do need human help on this one. Well this is the error:
Access to XMLHttpRequest at 'http://localhost:3001/api/validateQrCodeScan' from origin 'http://localhost:3000/' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Access to XMLHttpRequest at 'http://localhost:3001/api/validateQrCodeScan' from origin 'http://localhost:3000/' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I am testing it on localhost because its a new feature i am adding to my app. When i try to call this api i endpoint, same app, i get this error, and apparently none of the suggestions given by kappa works, not even the one that worked for the other developer. Wha makes me confuse is when i call the api from insomnia the thing works normally, but when i try to use it from the client, frontend, i get this cors error. The feature i am trying to implement is the following: a user scans a qr code, and a web page with a input field is shown, where a user provide a code that identifies him in the platform, the i send this code to the server via post request that triggers a
server-sent events (sse)
server-sent events (sse)
which will send this user info for a client that i subscribed to it, its basically a mechanism for users in a gym to validate their subscription status, and its info will be displayed in the gym monitors or any other devices. When i make this post request via other clients like insomnia, it works with no problem, the entire process, but from the fronted it doesn't
miho
miho3d ago
via other clients like insomnia, it works with no problem
Yep, because Insomnia is not a browser and doesn't send certain headers and expect certain responses that are CORS related 🙂 Could you share pieces of your code with us e.g. did you configure middleware for the API endpoint? Did you configure middleware in the server.setupFn? By default - if you did nothing - the CORS should work between the localhost client and the localhost server.
Filip
Filip3d ago
@Stefan Vitória That right, like Miho said, CORS errors are a browser-only thing. To understand more, read this message: https://discord.com/channels/686873244791210014/1265612049711501405/1265616768580190270

Did you find this page helpful?