Welcome 👋, in this blog, you will learn how to set up authentication with nextjs and make your website thrive.
If you don’t know how to set up supabase in nextjs. Then you can see 👇 post. How to connect Supabase and Nextjs
Step 1: Make a file named — auth.js in ‘pages/api’ folder.
import { supabase } from "../../utils/supabase";
export default function handler(request, response){
supabase.auth.api.setAuthCookie(request, response);
}
Step2: Go to file named — __app.js in ‘pages’ folder.
import "../styles/globals.css";
import { useState, useEffect } from "react";
// import { Toaster } from "react-hot-toast"; If you need, you can visit react-hot-toast.com for its documentation
import { supabase } from "../utils/supabase";
function MyApp({ Component, pageProps }) {
// We have made a state for knowing which is the current status of the user -- authenticated or not-authenticated
const [authenicated, setAuthenicated] = useState(null);
// 👇 it will trigger when the user first loads the website.
useEffect(() => {
// we are using supabase 'OnAuthStateChange', it's similar to firebase 'onAuthStateChanged'
const { data: authListener } = supabase.auth.onAuthStateChange(
(event, session) => {
handleAuthChange(event, session);
if (event === "SIGNED_IN") {
setAuthenicated("authenicated");
}
if (event === "SIGNED_OUT") {
setAuthenicated("not-authenicated");
}
}
);
// this is the function which is definded below.
checkUser();
// we are unsubscribing the checking of the user.dddddd
return () => {
authListener.unsubscribe();
};
}, []);
// this function will make the call to the api which we setuped.
async function handleAuthChange(event, session) {
await fetch("/api/auth", {
method: "POST",
headers: new Headers({ "Content-Type": "application/json" }),
credentials: "same-origin",
body: JSON.stringify({ event, session }),
});
}
// this will check if the user is authenticated or not
async function checkUser() {
const user = await supabase.auth.user();
if (user) {
setAuthenicated("authenticated");
}
if (!user) {
setAuthenicated("not-authenicated");
}
}
return (
<>
<Component {...pageProps} />
{/* <Toaster /> */} // this is loaded from react-hot-toast which you don't need. So, you can also delete it.
</>
);
}
export default MyApp;
Step 3: Make a file named — auth.jsx in ‘pages’ folder.
import React, { useState } from "react";
// import toast from "react-hot-toast"; This sends the notification to the user. You can check out react-hot-toast for it.
import { supabase } from "../utils/supabase";
function auth() {
const [email, setEmail] = useState(null);
const [loading, setLoading] = useState(false);
async function handleLogin(e) {
e.preventDefault();
setLoading(true);
if (email.length < 5) {
return toast.error("Please fill full email");
}
const { user, error } = await supabase.auth.signIn({
email: email,
});
if (!error) {
// toast("Please check your inbox", { icon: "📬" }); This sends the notification to the user. You can check out react-hot-toast for it.
}
if (error) {
// toast.error(error.message); This sends the notification to the user. You can check out react-hot-toast for it.
}
setLoading(false);
}
return (
<div>
<form action="" onSubmit={(e) => handleLogin(e)}>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<button type="submit">{loading ? "Logining in..." : "Submit"}</button>
</form>
</div>
);
}
export default auth;
Now, the authentication has been done.
🤔But how to fetch the user data?
It’s the server-side method, most the companies use server-side fetching for faster response:
import Head from "next/head";
import Image from "next/image";
import styles from "../styles/Home.module.css";
import { supabase } from "../utils/supabase";
export default function Home({ user }) {
return (
<div className={styles.container}>
<button onClick={(e) => supabase.auth.signOut()}>Logout</button>
{user.email}
</div>
);
}
export const getServerSideProps = async (context) => {
// It brings the data from cookies which is stored when we logged in the user.
const { user } = await supabase.auth.api.getUserByCookie(context.req);
// if we don't have user logined in, we can redirect him or her.
if (!user) {
return { redirect: { permanent: false, destination: "/auth", props: {} } };
}
// else we can send props.
return {
props: { user: user },
};
};
You can also use the second method for bringing the data: It’s client-side:
import Head from "next/head";
import Image from "next/image";
import styles from "../styles/Home.module.css";
import { supabase } from "../utils/supabase";
export default function Home({ }) {
const user = supabase.auth.user();
return (
<div className={styles.container}>
<button onClick={(e) => supabase.auth.signOut()}>Logoout</button>
{!user ? 'Loading' : user.email}
</div>
);
}
Congratulations, you have made your first website with authentication with supabase and nextjs.
For people who understand Hindi: // Embed YouTube Videos %[youtube.com/watch?v=ThQs_tCnODE]