npm i tutoruu-auth #npm
yarn add tutoruu-auth #yarn
pnpm add tutoruu-auth #pnpm
Set up API handler in pages/api/auth.ts
:
// /pages/api/auth.ts
import { createAuthAPIHandler } from 'tutoruu-auth';
export default createAuthAPIHandler();
Set up AuthContext
in _app.tsx
:
// /pages/_app.tsx
import { AuthContext } from 'tutoruu-auth';
export default function App({ Component, pageProps }) {
return (
<AuthContext>
<Component {...pageProps} />
</AuthContext>
);
}
Add auth screen in pages/auth.tsx
:
// /pages/auth.tsx
import { useAuth } from 'tutoruu-auth';
import { useEffect } from 'react';
export default function Auth() {
const { protect } = useAuth();
useEffect(() => {
protect(() => {
window.location.replace(
window.location.href.split('?')[1]?.split('=')[1] ?? '/'
);
});
}, []);
}
You can use the createSSRAuthentication
Helper to protect pages from being accessed by unauthenticated users.
If a user is not authenticated, they will be redirected to the login page, and then back to the page they were trying to access.
import { createSSRAuthentication } from 'tutoruu-auth';
export const getServerSideProps = createSSRAuthentication();
// or with callback
export const getServerSideProps = createSSRAuthentication((ctx) => {
// do something
console.log('will log in before reaching this code');
});
import { useAuth } from 'tutoruu-auth';
export const Component: FC = () => {
const { protect, redirect, session } = useAuth();
const login = () => {
protect(() => {
// do something
console.log('will log in before reaching this code');
redirect('/dashboard'); // redirect with token appended to url
});
};
if (session?.user) return <div>User is {session.user.name}</div>;
else return <button onClick={login}>Log in</button>;
};
Shows a button that logs in the user if they are not logged in, and shows their image if they are logged in.
import { UserButton } from 'tutoruu-auth';
const Navbar: FC = () => {
return (
<div>
<UserButton />
</div>
);
};
You can use the createAuthenticatedRoute
helper to protect endpoints from being accessed by unauthenticated users.
import { createAuthenticatedRoute } from 'tutoruu-auth'
export const handler = createAuthenticatedRoute({
onAuthenticated: async (req, res) => {
// do something
console.log("will log in before reaching this code");
},
onLoggedOut: async (req, res) => {
// do something
console.log("If the user is not logged in, this code will run");
}
);