Episode 43 of 44

Posting to Firebase

Connect Vue to Firebase — send blog post data to a Firebase Realtime Database using HTTP POST requests.

Posting to Firebase

Let us connect the blog application to a real database. Firebase Realtime Database provides a free, cloud-hosted JSON database with a REST API — no backend code needed.

Setting Up Firebase

  1. Go to console.firebase.google.com
  2. Create a new project
  3. Go to Realtime Database and create a database
  4. Start in "test mode" for development (allows read/write without auth)
  5. Copy the database URL (e.g., https://your-project.firebaseio.com)

Posting Data

// In the AddBlog component
methods: {
    addPost() {
        this.$http.post(
            'https://your-project.firebaseio.com/posts.json',
            this.blog
        ).then(response => {
            console.log('Saved!', response);
            this.$router.push('/');
        });
    }
}

Firebase's REST API accepts POST requests. The .json suffix is required for the Realtime Database REST API. Firebase auto-generates a unique key for each record.

What Firebase Stores

{
    "posts": {
        "-NaB1cD2eF3gH4iJ": {
            "title": "My First Post",
            "content": "This is the post content",
            "categories": ["Vue", "JavaScript"],
            "author": "Shaun"
        },
        "-NaB5kL6mN7oP8qR": {
            "title": "Second Post",
            "content": "Another post",
            "categories": ["CSS"],
            "author": "Mario"
        }
    }
}

Redirecting After Save

this.$router.push('/');  // Navigate to home after saving

After a successful POST, use this.$router.push() to redirect the user back to the blog list.

Key Takeaways

  • Firebase Realtime Database provides a REST API — POST data to https://project.firebaseio.com/collection.json
  • this.$http.post(url, data) sends the blog object to Firebase
  • Firebase auto-generates unique keys for each record
  • Redirect after saving with this.$router.push('/')