Authentication protection for Next.JS pages and routes, powered by NextAuth.js ๐
- Protect API routes
- Protect pages
- Protect pages before rendering
To read the full documentation, visit this document.
- Fastest way to add authentication protection: with just a few lines of code you can protect every page and API route of your application!
- Almost zero initial configuration: you just need to pass your already created NextAuth.js configuration object, and you're ready to go!
next-auth-protection
will use that config to optimize the verification process. - Flexible and compatible with every NextJS & NextAuth.js applications: works with every provider, adaptar and database supported by NextAuth.js.
To start using Next Auth Protection, install the package:
# npm
npm install next-auth-protection
# yarn
yarn add next-auth-protection
To start using Next Auth Protection, follow these steps:
- Initialize NextAuth.js ๐
Make sure you have at least one provider set up and working in your project and you're wrapping your application with the <SessionProvider>
component (needed in the package's page
protector).
- Create your
WithAuthProtection
instance ๐ก๏ธ
Using your NextAuth.js configuration object, create a new instance of WithAuthProtection
:
import { WithAuthProtection } from 'next-auth-protection';
const authProtection = new WithAuthProtection(NEXTAUTH_OPTIONS);
- Protect your routes ๐
You can protect your routes in three ways:
const authProtection = new WithAuthProtection(NEXTAUTH_OPTIONS);
// 1 - protect pages directly
const MyPage = authProtection.page(() => {
return <h1>My page</h1>;
});
// 2 - protect pages before rendering
export const getServerSideProps = authProtection.getServerSideProps(() => {
return {
props: {
message: 'Hello world',
},
};
});
// 3 - protect API routes
const handler = authProtection.api(async (req, res) => {
res.status(200).json({ message: 'Hello world' });
});
- Optional: customize the redirect behavior ๐ฆ