User authentication

SaaSInMinutes uses Supabase Auth for authentication. This tutorial shows you how to set up user authentication in your app.

Setup Supabase Auth

First, create a Supabase project and get your credentials:

  1. Go to supabase.com and create an account
  2. Create a new project
  3. Go to Settings → API and copy your URL and anon key
  4. Add them to your .env.local file

Configure environment variables

.env.local
1SUPABASE_URL=https://your-project.supabase.co
2SUPABASE_ANON_KEY=your-anon-key
3NEXTAUTH_SECRET=your-secret-key-min-15-chars
4NEXTAUTH_URL=http://localhost:3000

Create a login page

Create a login page at app/login/page.tsx:

app/login/page.tsx
1'use client';
2
3import { useState } from 'react';
4import { createClient } from '@/libs/supabase';
5
6export default function LoginPage() {
7  const [email, setEmail] = useState('');
8  const [password, setPassword] = useState('');
9  const supabase = createClient();
10
11  const handleLogin = async (e: React.FormEvent) => {
12    e.preventDefault();
13    const { data, error } = await supabase.auth.signInWithPassword({
14      email,
15      password,
16    });
17    if (error) {
18      console.error('Error:', error.message);
19    } else {
20      window.location.href = '/dashboard';
21    }
22  };
23
24  return (
25    <form onSubmit={handleLogin}>
26      <input
27        type="email"
28        value={email}
29        onChange={(e) => setEmail(e.target.value)}
30        placeholder="Email"
31      />
32      <input
33        type="password"
34        value={password}
35        onChange={(e) => setPassword(e.target.value)}
36        placeholder="Password"
37      />
38      <button type="submit">Login</button>
39    </form>
40  );
41}

Protect routes

Create a middleware to protect your routes:

middleware.ts
1import { createMiddlewareClient } from '@supabase/auth-helpers-nextjs';
2import { NextResponse } from 'next/server';
3import type { NextRequest } from 'next/server';
4
5export async function middleware(req: NextRequest) {
6  const res = NextResponse.next();
7  const supabase = createMiddlewareClient({ req, res });
8
9  const {
10    data: { session },
11  } = await supabase.auth.getSession();
12
13  if (!session && req.nextUrl.pathname.startsWith('/dashboard')) {
14    return NextResponse.redirect(new URL('/login', req.url));
15  }
16
17  return res;
18}
19
20export const config = {
21  matcher: ['/dashboard/:path*'],
22};

Get current user

Get the current user in your server components:

app/dashboard/page.tsx
1import { createServerComponentClient } from '@supabase/auth-helpers-nextjs';
2import { cookies } from 'next/headers';
3
4export default async function DashboardPage() {
5  const supabase = createServerComponentClient({ cookies });
6  const {
7    data: { session },
8  } = await supabase.auth.getSession();
9
10  if (!session) {
11    redirect('/login');
12  }
13
14  return (
15    <div>
16      <h1>Welcome, {session.user.email}!</h1>
17    </div>
18  );
19}

Next steps

Now that you have authentication set up, you can: