Secure CORS handling using next.js and cloud functions
P粉106301763
P粉106301763 2024-03-29 11:35:12
0
1
373

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粉106301763
P粉106301763

reply all(1)
P粉523335026

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"
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!