Deploy Firebase Functions with Bolt.new 🚀

Important Note: When working in Bolt.new (StackBlitz), you can’t directly deploy Firebase Functions from the web environment. This guide shows you how to use Google Cloud Shell as a deployment solution.

What You’ll Need

  1. Prerequisites:

    • Google account (same one you use for Firebase)
    • Firebase project set up in Firebase Console
    • Your Bolt.new project ready to go
  2. Tools We’ll Use:

    • Google Cloud Shell (free, browser-based development environment)
    • Firebase CLI
    • Basic terminal knowledge

Deployment Process

1. Access Google Cloud Shell

  1. Visit cloud.google.com/shell
  2. Click “Start Cloud Shell”
  3. Wait for environment initialization (~30 seconds)

2. Set Up Your Working Space

# Create and enter a new directory
mkdir my-firebase-functions
cd my-firebase-functions

# Initialize Firebase
firebase init functions

When prompted during initialization:

  • Choose “Yes” to proceed
  • Select your Firebase project
  • Choose JavaScript or TypeScript
  • Skip ESLint for now (say “No”)
  • Install dependencies (say “Yes”)

3. Write Your Functions

You have two options for editing:

  1. Cloud Shell Editor:

    • Click the pencil icon (“Open Editor”)
    • Navigate to functions/index.js
  2. Terminal Editor:

    nano functions/index.js

Here’s a basic example function:

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

// HTTP Function Example
exports.helloWorld = functions.https.onRequest((request, response) => {
  response.send("Hello from Firebase!");
});

// Firestore Trigger Example
exports.onUserCreated = functions.firestore
  .document('users/{userId}')
  .onCreate((snap, context) => {
    const newUser = snap.data();
    console.log('New user created:', newUser);
    return null;
  });

// Storage Trigger Example
exports.onFileUploaded = functions.storage
  .object()
  .onFinalize(async (object) => {
    console.log('File uploaded:', object.name);
    return null;
  });

4. Deploy Your Functions

# Deploy all functions
firebase deploy --only functions

# Deploy specific function
firebase deploy --only functions:functionName

Function Types

1. HTTP Functions

exports.api = functions.https.onRequest((req, res) => {
  // Check request method
  if (req.method !== 'POST') {
    res.status(405).send('Method Not Allowed');
    return;
  }

  // Handle CORS
  res.set('Access-Control-Allow-Origin', '*');

  // Process request
  const data = req.body;
  res.json({ received: data });
});

2. Firestore Triggers

exports.onDocumentUpdate = functions.firestore
  .document('collection/{docId}')
  .onUpdate((change, context) => {
    const newData = change.after.data();
    const previousData = change.before.data();
    
    // Your logic here
    return null;
  });

3. Storage Triggers

exports.processUpload = functions.storage
  .object()
  .onFinalize(async (object) => {
    const filePath = object.name;
    const contentType = object.contentType;
    
    // Your processing logic here
    return null;
  });

Best Practices

  1. Error Handling
exports.robustFunction = functions.https.onRequest(async (req, res) => {
  try {
    // Your function logic
    const result = await someOperation();
    res.json({ success: true, data: result });
  } catch (error) {
    console.error('Function failed:', error);
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});
  1. Environment Variables
// In Cloud Shell:
firebase functions:config:set api.key="your-api-key"

// In your function:
const apiKey = functions.config().api.key;
  1. Function Timeouts
exports.longRunningTask = functions
  .runWith({
    timeoutSeconds: 300,
    memory: '1GB'
  })
  .https.onRequest(async (req, res) => {
    // Your long-running task here
  });

Common Issues

1. Authentication Issues

If you see “Not authorized” errors:

firebase login

2. Dependencies Missing

If Firebase CLI is not found:

npm install -g firebase-tools

3. Session Expiration

Cloud Shell sessions expire after 1 hour of inactivity. If this happens:

  1. Refresh the Cloud Shell page
  2. Navigate back to your project directory
  3. Continue where you left off

Important Notes

  1. Code Management

    • Keep function code in version control
    • Document environment variables
    • Maintain local backups
  2. Development Flow

    • Write and test functions locally first
    • Use emulators for testing
    • Deploy only when ready
  3. Security

    • Always validate input data
    • Use appropriate IAM roles
    • Implement rate limiting

Remember

  • Cloud Shell sessions are temporary
  • Save your work frequently
  • Keep function code in your Bolt.new project
  • Use Cloud Shell only for deployments

Need Help?