Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nest and HTTP function - CORS

I'm trying to utilize Nest with a Firebase HTTP function, but am hitting a CORS error when calling from the client.

This was my setup before:

declare const require: any
const functions = require('firebase-functions')
const cors = require('cors')({ origin: true })
const express = require('express')

const app = express()
app.use(cors)
const cb = (req, res) => res.status(200).send('success')
app.use(cb)

export default functions.https.onRequest(app)

The above worked fine (with a Cloud Functions Invoker role set with allAuthenticatedUsers).

This is my new setup with Nest:

import * as functions from 'firebase-functions'
import { NestFactory } from '@nestjs/core'
import { ExpressAdapter } from '@nestjs/platform-express'
import { Api_Module } from './api.module'
import express from 'express'

const server = express()

const create_nest_server = async (express_instance: express.Express) => {
  const adaptor = new ExpressAdapter(express_instance)
  const app = await NestFactory.create(Api_Module, adaptor)
  app.enableCors({ origin: true })
  await app.init()
  return app
}


create_nest_server(server)
    .then(v => console.log('Nest Ready'))
    .catch(err => console.error('Nest broken', err))


export default functions.https.onRequest(server)

(from https://fireship.io/snippets/setup-nestjs-on-cloud-functions/)

This yields Access to fetch at 'https://us-central1-<project>.cloudfunctions.net/api-default/' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. on the client.

I've also tried a couple other things such as:

declare const require: any
const cors = require('cors')({ origin: true })

const server = express()
server.use(cors)
// ...the rest

And:

const create_nest_server = async (express_instance: express.Express) => {
  const adaptor = new ExpressAdapter(express_instance)
  const app = await NestFactory.create(Api_Module, adaptor, {
    cors: {
      origin: true,
    }
  })

  app.enableCors()
  await app.init()
  return app
}

And:

  const nestApp = await NestFactory.create(AppModule, adapter, {
    logger: new CoreLogger(),
    cors: {
      origin: '*',
      methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
      credentials: true,
      preflightContinue: false,
      optionsSuccessStatus: 204,
    },
  })

As well as using app.enableCors() without any arguments.

Help is greatly appreciated.

like image 277
skwny Avatar asked Feb 20 '26 20:02

skwny


1 Answers

Assuming your client is an Angular app, if you are running a local development version of your client, you could use a proxy config file to make your requests appear as if they're coming from the same origin:

proxy.conf.json

{
    "/api-default": {
        "target": "https://us-central1-<project>.cloudfunctions.net",
        "logLevel": "debug"
    }
}

You'll need to configure this file according to how you are calling your api, then start your local app with the following command: ng serve --proxy-config proxy.conf.json

An alternative would be to add the appropriate CORS response headers in your NestJS responses:

@Post()
@Header('Access-Control-Allow-Origin', 'http://localhost:4200')
create() {
  return 'This action adds a new cat';
}

This would tell the client that that the server allows the provided origin.

like image 181
FrostyZombi3 Avatar answered Feb 22 '26 10:02

FrostyZombi3



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!