Magic Link Authentication and Route Controls with Supabase and Next.js

Nader Dabit
8 min readJul 13, 2021

While Supabase is widely known for their real-time database and API layer, one of the things I like about it is the number of easy to set up authentication mechanisms it offers out of the box.

Magic Link

One of my favorites is Magic Link. You've probably used magic link in the past. Magic link sends a link to the user via email containing a link to authenticate with the service via a custom URL and access token.

When the user visits the URL, a session is set in their browser storage and the user is redirected back to the app, authenticating the user in the process.

This is becoming a very popular way to authenticate users as they do not have to keep up with another password, it provides a really great user experience.

Next.js

With Next.js, you have the ability to not only protect routes with client-side authorization, but for added security you can do server-side authorization and redirects in getServerSideProps if a cookie has been set and is available in the request context.

This is also where Supabase comes in handy. There is built-in functionality for setting and getting the cookie for the signed in user in SSR and API routes:

Setting the user in an API route

import { supabase } from '../../client'

export default function handler(req, res) {
supabase.auth.api.setAuthCookie(req, res)
}

Getting the user in an SSR or API route

export async function getServerSideProps({ req }) {
const { user } = await supabase.auth.api.getUserByCookie(req)

if (!user) {
return {
props: {}
}
}

return { props: { user } }
}

Server-side redirects are typically preferred over client-side redirects from an SEO perspective - it's harder for search engines to understand how client-side redirects should be treated.

You are also able to access the user profile from an API route using the getUserByCookie function, opening up an entirely new set of use cases and functionality.

--

--

Nader Dabit

Full Stack Product Engineer, Author, Teacher, Director of Developer Relations at Avara