Blog>
Snippets

Adding Firebase Authentication

Provide an example of using Firebase to add authentication to a Next.js app with setup steps and a sign-in component example.
import { initializeApp } from 'firebase/app';
import { getAuth, signInWithEmailAndPassword } from 'firebase/auth';

// Firebase configuration object containing keys and identifiers for your app
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',
  measurementId: 'your-measurement-id'
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);

export { auth, signInWithEmailAndPassword };
Initialize Firebase and export the `auth` object and the `signInWithEmailAndPassword` method for use in the authentication process.
import React, { useState } from 'react';
import { auth, signInWithEmailAndPassword } from '../path/to/firebaseConfig';

const SignInComponent = () => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const handleSignIn = async (event) => {
    event.preventDefault();
    try {
      const userCredential = await signInWithEmailAndPassword(auth, email, password);
      const user = userCredential.user;
      console.log('Logged in user:', user);
    } catch (error) {
      console.error('Error signing in with email and password', error);
    }
  };

  return (
    <form onSubmit={handleSignIn}>
      <input
        type='email'
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        placeholder='Email'
      />
      <input
        type='password'
        value={password}
        onChange={(e) => setPassword(e.target.value)}
        placeholder='Password'
      />
      <button type='submit'>Sign In</button>
    </form>
  );
};

export default SignInComponent;
Create a `SignInComponent` that includes a form for users to input their email and password and sign in. The component uses the `signInWithEmailAndPassword` method provided by Firebase on form submission.
import '../path/to/firebaseConfig';
import SignInComponent from '../path/to/SignInComponent';

function LoginPage() {
  return (
    <div>
      <h1>Login</h1>
      <SignInComponent />
    </div>
  );
}

export default LoginPage;
Import the configured Firebase authentication and `SignInComponent`. Create a `LoginPage` component that contains the `SignInComponent` for users to log in.