Authentication
JWT
For NextJS

How to use JWT authentication system ?

Note: The uko template uses the firebase authentication system by default.

  • Step-1 : Open the src/app/layout.jsx file then import the AuthProvider from src/contexts/jwtContext and wrap the Root Layout component with it.

  • Step-2 : Open the src/hooks/useAuth.js file. Thereupon, import the AuthContext from src/contexts/jwtContext then pass AuthContext as a argument in useContext hook.

  • Step-3 : Call the useAuth hook inside AuthGuard, GuestGuard components, Login, Register page etc.

Step 1

layout.jsx

_10
import { AuthProvider } from "contexts/jwtContext";
_10
_10
const RootLayout = ({ children }) => {
_10
return <AuthProvider>{children}</AuthProvider>;
_10
};
_10
_10
export default RootLayout;

Step 2

useAuth.js

_10
import { AuthContext } from "contexts/jwtContext";
_10
_10
const useAuth = () => useContext(AuthContext);
_10
export default useAuth;

Step 3

login.jsx

_17
import useAuth from "hooks/useAuth";
_17
_17
const Login = () => {
_17
const { login } = useAuth();
_17
_17
const onLogin = () => {
_17
login("example@email.com", "pass123"); // Login crediential
_17
};
_17
_17
return (
_17
<Box>
_17
<Button onClick={onLogin}>Login</Button>
_17
</Box>
_17
);
_17
};
_17
_17
export default Login;

profile.jsx

_18
import useAuth from "hooks/useAuth";
_18
_18
const Profile = () => {
_18
const { user, isAuthenticated, logout } = useAuth();
_18
_18
if (isAuthenticated && user) {
_18
return (
_18
<Box>
_18
<Typography>Email : {user.email}</Typography>
_18
<Button onClick={logout}>logout</Button>
_18
</Box>
_18
);
_18
}
_18
_18
return <Redirect to="/login" />;
_18
};
_18
_18
export default Profile;

How to delete from app ?

  • Delete the jwtContext.jsx file from src/contexts folder
  • In addition, if you use this, remove it from the src/hooks/useAuth.js file.