I am new to Google cloud. But here is what I want to accomplish.
I want to call a Cloud Function in a secure way. What are the steps in creating identity, secret and how to use it in sample next.js app invoking java cloud function.
Hello @CookieKing02020 ,Welcome on Google Cloud Community.
Creating Identity (Service Account):
Creating Secrets:
Using Identity and Secrets in Next.js App:
import { SecretManagerServiceClient } from '@google-cloud/secret-manager';
import fetch from 'node-fetch';
// Function to retrieve secret from Secret Manager
async function getSecret(secretName) {
const client = new SecretManagerServiceClient();
const [version] = await client.accessSecretVersion({
name: `projects/YOUR_PROJECT_ID/secrets/${secretName}/versions/latest`, // Replace YOUR_PROJECT_ID and secretName with actual values
});
const payload = version.payload.data.toString('utf8');
return payload;
}
// Example usage within a Next.js API route
export default async function handler(req, res) {
try {
// Retrieve secret from Secret Manager
const mySecret = await getSecret('my-secret');
// Do something with the secret
console.log('My secret:', mySecret);
// Make a request to your Java Cloud Function
const functionUrl = 'https://REGION-PROJECT_ID.cloudfunctions.net/FUNCTION_NAME';
const response = await fetch(functionUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
// Add any additional headers if required
},
body: JSON.stringify({
// Add any data you need to pass to your Cloud Function
secret: mySecret,
// Add any other parameters here
}),
});
// Check if the request was successful
if (response.ok) {
// Handle the response from the Cloud Function
const result = await response.json();
console.log('Cloud Function response:', result);
res.status(200).json(result);
} else {
console.error('Error invoking Cloud Function:', response.statusText);
res.status(500).json({ error: 'Error invoking Cloud Function' });
}
} catch (error) {
console.error('Error:', error.message);
res.status(500).json({ error: 'Internal Server Error' });
}
}
Remember to replace 'YOUR_PROJECT_ID'
, 'my-secret'
, 'REGION-PROJECT_ID.cloudfunctions.net/FUNCTION_NAME'
, and any other placeholders with the actual values corresponding to your Google Cloud project, Secret Manager secret, and Java Cloud Function.
Save this code in a file under the pages/api/
directory in your Next.js app, and it will create an API route that retrieves a secret from Secret Manager and invokes your Java Cloud Function with that secret.
PS: Dunno if this code will work 😄 I've used gemini for generating this code as I'm not such an expert with JS 🙂
Creating secret: https://cloud.google.com/secret-manager/docs/create-secret-quickstart#secretmanager-quickstart-gclou...
--
cheers,
DamianS
LinkedIn medium.com Cloudskillsboost