Using Cookie-Based Authentication in Next.js 13 App Router 🍪

Posted by






Implement cookie-based Auth in the Next.js 13 App Router 🍪

Implement cookie-based Auth in the Next.js 13 App Router 🍪

Next.js is a popular framework for building React applications, and with the recent release of version 13, it has brought some exciting new features. One of these features is the ability to implement cookie-based authentication in the Next.js app router.

In order to implement cookie-based authentication, you first need to make sure that your backend API is able to set and read cookies. This can be done using a library like Express.js or any other server-side framework that supports cookies.

Once your backend is able to handle cookies, you can then use the Next.js app router to implement authentication. This can be done by adding a piece of middleware to the router that checks for a valid authentication cookie before allowing access to the protected routes.

Here’s an example of how you can implement cookie-based authentication in the Next.js 13 app router:

“`jsx
const withAuth = (handler) => async (req, res) => {
const { cookies } = req;

if (!cookies.authToken) {
res.writeHead(302, { Location: “/login” });
res.end();
return;
}

// Add additional logic to validate the auth token if needed

return handler(req, res);
};

const protectedRouteHandler = (req, res) => {
// Logic for handling the protected route
res.end(“You have access to the protected route”);
};

export default function ProtectedRoutePage() {
return (

Protected Route

This route is protected by cookie-based authentication

);
}

export const getServerSideProps = withAuth(protectedRouteHandler);
“`

In this example, we define a higher-order function called `withAuth` that takes a route handler as its argument and returns a new function. This new function checks for the presence of an `authToken` cookie in the request object and redirects the user to the login page if it is not found. If the cookie is present, the original route handler is called.

We then use the `withAuth` function as the `getServerSideProps` for our protected route page. This ensures that the authentication check is performed server-side before the page is rendered, adding an extra layer of security.

By implementing cookie-based authentication in the Next.js 13 app router, you can ensure that only authorized users are able to access certain parts of your application. This can help to prevent unauthorized access and protect sensitive information.

So why not try implementing cookie-based authentication in your Next.js 13 app router today? 🍪


0 0 votes
Article Rating
30 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Tom Watkins
11 months ago

Deprecation the libraries on the video for the ssr library only a few months after releasing the tutorial is a tad concerning. That being said, very easy to follow and use

mickmister
11 months ago

These short videos put into a playlist is a great way to deliver this content. Thanks so much! Supabase is so awesome

Ro11ingBoy
11 months ago

This guy is so good

Jorim S
11 months ago

you are talking too fast

Aymane
11 months ago

how supabase connects to our database if we're not passing any url or key to createServerComponentClient or createClientComponentClient ? 🤫

0xtz
11 months ago

Hi please 👋, I can't get the user id from a client component please??? 😅

Matt Waldron
11 months ago

Is it possible to authenticate a user server-side without next.js? What about for example, using React Native with a serverless backend?

Alucard
11 months ago

what about when user logout using supabase.auth.signOut function, it doesnt' delete the token from cookies, so when user reloads their browser.

Boris Barzotto
11 months ago

how to specify another schema? auth-helpers-next only works with "public", thx mate

Ali Onar
11 months ago

I started Supabase eagerly but Supabase is getting on my nerves. I don't think the videos and documents are self explanatory. It's very confusing.

Moha
11 months ago

it doesn't work when the email confirmation is disabled, I'm getting this error "PKCE flow is not supported on signups with autoconfirm enabled" I've searched all the docs , found nothing!
any help?

nestor martinez
11 months ago

is this code used only if you use email redirect right?

단테
11 months ago

super simple

Vladyslav Melnychenko
11 months ago

Have you considered not adding changes to integration workflow with every release? Every time I start a new project with supabase I have to learn all docs again.

kay mak
11 months ago

Thanks for this video! In your previous cookie auth video, you mentioned that NextJS has a bug with GET requests and cookies where cookies are not properly piped through (they're totally missing, in fact): https://youtu.be/KmJN-bEayeY?t=595. This still seems to be the case for me next 13.4.7, but in this video it seems that you're no longer experiencing this bug?

Psyfer Inc.
11 months ago

so frustrating

Ellis Otoo
11 months ago

Im unable to redirect to the accounts page after deployment when I click the magic link in the email its always redirects to localhost during production,

Mike J
11 months ago

How do you handle redirects with the code exchange? E.g for a regular login I want to redirect to the main content, but for a password reset I'd want to redirect to a password reset page.

Nico Cabral
11 months ago

Hi, How do you set cookie expiration? Say once the user is login it expires for 1hr and the user is automatically logout