search

Home  >  Q&A  >  body text

Secure CORS handling using next.js and cloud functions

I use next.js on the front end, and there is an "api" folder that provides us with a node.js environment on the next.js server side.

We can have some proxy "api" between frontend and backend (cloud functions).

  1. From the frontend, I send a request to next.js api
  2. Send request from next/api to cloud function
  3. Get the response on the front end and return it

Result: Get CORS

Next.js api proxy code:

import { getFunctions, httpsCallable } from 'firebase/functions';

import { firebase } from '@/lib';

export async function deleteUserAccount(userId: string) {
  if (!userId) {
    console.error('deleteUserAccount: no userId provided');
    return;
  }

  try {
    const functions = getFunctions(firebase, 'us-central1');
    const deleteUserData = httpsCallable(functions, 'deleteUserData');

    const { data }: any = await deleteUserData({
      userId,
    });

    console.log('deleteUserAccount', data);
  } catch (error) {
    console.error('deleteUserAccount error', error);
  }
}

This is the cloud function implementation:

const admin = require('firebase-admin');
const functions = require('firebase-functions');

exports.deleteUserData = functions.https.onRequest(async (req, res) => {
    const uid = request.auth.uid;
    
    try {
        await admin.auth().deleteUser(uid);
        return { message: 'Data deleted successfully!' };
    } catch (error) {
        console.error('Error deleting user data', error);
        return Promise.reject(error);
    }
});

How to resolve CORS securely?

P粉106301763P粉106301763238 days ago419

reply all(1)I'll reply

  • P粉523335026

    P粉5233350262024-03-30 09:43:56

    The Firebase repository explains the use of cors in two examples. Your question has been answered here Just make sure you use this format

    {
    origin:"https://your-site.name"
    }
    

    reply
    0
  • Cancelreply