Categories We Write About

Build a birthday tracker with notifications

To build a birthday tracker with notifications, you can create a simple web or mobile app that tracks birthdays and sends reminders when someone’s birthday is coming up. Here’s a basic outline of how to do this:

Tools and Technologies:

  1. Frontend:

    • HTML, CSS, JavaScript (for the web interface)

    • React or Angular for a more dynamic interface (optional)

  2. Backend:

    • Node.js with Express (for server-side logic)

    • Database: MongoDB (for storing user data and birthdays)

  3. Notifications:

    • Push notifications (e.g., using Firebase Cloud Messaging or Web Push)

    • Email notifications (using an email service like SendGrid or SMTP)

Step-by-Step Guide:

1. Set up your frontend (User Interface)

  • A simple form where users can input their friend’s name, birthdate, and email address (optional).

  • A list view showing upcoming birthdays and an option to mark birthdays as remembered.

Basic HTML Form:

html
<form id="birthday-form"> <input type="text" id="name" placeholder="Name" required> <input type="date" id="birthdate" required> <input type="email" id="email" placeholder="Email (optional)"> <button type="submit">Add Birthday</button> </form> <div id="birthday-list"> <!-- List of upcoming birthdays will appear here --> </div>

Simple CSS:

css
body { font-family: Arial, sans-serif; } #birthday-form { margin: 20px; } #birthday-list { margin-top: 20px; }

Basic JavaScript for Adding Data:

javascript
const form = document.getElementById("birthday-form"); const birthdayList = document.getElementById("birthday-list"); form.addEventListener("submit", function(event) { event.preventDefault(); const name = document.getElementById("name").value; const birthdate = document.getElementById("birthdate").value; const email = document.getElementById("email").value; // Call API to save this data to your backend fetch('/api/birthdays', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ name, birthdate, email }) }) .then(response => response.json()) .then(data => { alert("Birthday added!"); updateBirthdayList(); // refresh the birthday list }); }); function updateBirthdayList() { // Fetch upcoming birthdays from your backend fetch('/api/upcoming-birthdays') .then(response => response.json()) .then(data => { birthdayList.innerHTML = ''; data.forEach(birthday => { const div = document.createElement('div'); div.innerHTML = `${birthday.name} - ${birthday.birthdate}`; birthdayList.appendChild(div); }); }); } // Initial load of the birthday list updateBirthdayList();

2. Backend:

Create an API using Node.js and Express to handle the storage and retrieval of birthday data.

Install Dependencies:

bash
npm init -y npm install express mongoose body-parser

Set up the server (server.js):

javascript
const express = require('express'); const mongoose = require('mongoose'); const bodyParser = require('body-parser'); const app = express(); const PORT = process.env.PORT || 3000; app.use(bodyParser.json()); mongoose.connect('mongodb://localhost:27017/birthday-tracker', { useNewUrlParser: true, useUnifiedTopology: true }); const birthdaySchema = new mongoose.Schema({ name: String, birthdate: Date, email: String, }); const Birthday = mongoose.model('Birthday', birthdaySchema); // API route to add birthday app.post('/api/birthdays', (req, res) => { const { name, birthdate, email } = req.body; const newBirthday = new Birthday({ name, birthdate, email }); newBirthday.save() .then(() => res.json({ message: 'Birthday added successfully' })) .catch(err => res.status(400).json({ error: err.message })); }); // API route to get upcoming birthdays app.get('/api/upcoming-birthdays', (req, res) => { const today = new Date(); Birthday.find({ birthdate: { $gte: today, } }).sort({ birthdate: 1 }) .then(birthdays => res.json(birthdays)) .catch(err => res.status(400).json({ error: err.message })); }); app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });

3. Sending Notifications:

You can use a service like Firebase Cloud Messaging (FCM) to send push notifications to users when their friends’ birthdays are approaching. Here’s a basic guide to implement this:

  • Firebase Setup:

    1. Create a Firebase project at https://console.firebase.google.com.

    2. Add Firebase to your app and obtain the firebase-messaging-sw.js file and Firebase credentials.

  • Web Push Notification Service:

    1. In your service worker (firebase-messaging-sw.js), set up the push service:

    javascript
    importScripts('https://www.gstatic.com/firebasejs/9.1.3/firebase-app.js'); importScripts('https://www.gstatic.com/firebasejs/9.1.3/firebase-messaging.js'); const firebaseConfig = { apiKey: "YOUR_API_KEY", authDomain: "YOUR_AUTH_DOMAIN", projectId: "YOUR_PROJECT_ID", storageBucket: "YOUR_STORAGE_BUCKET", messagingSenderId: "YOUR_MESSAGING_SENDER_ID", appId: "YOUR_APP_ID" }; firebase.initializeApp(firebaseConfig); const messaging = firebase.messaging(); messaging.onBackgroundMessage(function(payload) { const notificationTitle = 'Birthday Reminder'; const notificationOptions = { body: payload.data.message, icon: '/icons/icon-192x192.png', }; self.registration.showNotification(notificationTitle, notificationOptions); });
  • Send Push Notifications from Server:
    Use Firebase Admin SDK in your server to send notifications when a birthday is approaching.

    Install Firebase Admin SDK:

    bash
    npm install firebase-admin

    Initialize Firebase Admin in server.js:

    javascript
    const admin = require('firebase-admin'); admin.initializeApp({ credential: admin.credential.applicationDefault(), }); function sendBirthdayReminder(fcmToken, message) { const payload = { notification: { title: 'Birthday Reminder', body: message, } }; admin.messaging().sendToDevice(fcmToken, payload) .then(response => { console.log("Successfully sent message:", response); }) .catch(error => { console.log("Error sending message:", error); }); }

    Schedule a daily job (using something like node-cron) to check for upcoming birthdays and send reminders.

4. Email Notifications (Optional):

If you’d like to send email reminders as well, you can use a service like SendGrid.

  • Install SendGrid:

bash
npm install @sendgrid/mail
  • Send Email:

    javascript
    const sgMail = require('@sendgrid/mail'); sgMail.setApiKey('YOUR_SENDGRID_API_KEY'); function sendBirthdayEmail(email, name) { const msg = { to: email, from: 'your-email@example.com', subject: 'Upcoming Birthday Reminder', text: `Hey! Don't forget that ${name}'s birthday is coming up soon.`, }; sgMail.send(msg) .then(() => console.log('Email sent')) .catch(error => console.error(error)); }

Final Considerations:

  • Privacy and Security: Ensure that you protect users’ data, especially if you’re storing sensitive information like emails. Implement proper authentication and validation.

  • User Interaction: You can add functionality to allow users to edit or delete birthday entries, or to mark birthdays as “celebrated.”

  • Mobile App: You could build a mobile version using React Native or Flutter for native notifications.

With these basic steps, you’ll have a fully functional birthday tracker with push notifications, email reminders, and a simple user interface!

Share This Page:

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Categories We Write About