Reputation: 23
I am implementing authentication in my NextJS app using next-iron-session
, currently using getServerSideProps
method for that an it is working fine but I have to implement this in every page where I want to authenticate the user. I just want to implement it in HOC format or wrapper format so I don't have to rewrite this in every file. I am using the following code for that
import { withIronSession } from "next-iron-session";
const user_home = (props) => {
if (!user.isAuth) {
router.push("/");
}
// ...some other layout stuff
};
export const getServerSideProps = withIronSession(
async ({ req, res }) => {
const user = req.session.get("user");
if (!user) {
return {
props: { isAuth: false },
};
}
return {
props: { isAuth: true, user: user },
};
},
{
cookieName: "NEXT_EXAMPLE",
cookieOptions: {
secure: true,
},
password: process.env.APPLICATION_SECRET,
}
);
export default user_home;
Upvotes: 1
Views: 1680
Reputation: 1055
This post is a bit old but here is my solution, with iron-session since next-iron-session
has been deprecated.
Create a HOC like this
import { withIronSessionSsr } from "iron-session/next";
import { sessionOptions } from "./session";
const WithAuth = (gssp) =>
withIronSessionSsr(async function (context) {
const user = context.req.session.user;
// you can check the user in your DB here
if (!user) {
return {
redirect: {
permanent: false,
destination: "/login",
},
}
}
return await gssp(context);
}, sessionOptions);
export default WithAuth;
Then in your page
export const getServerSideProps = WithAuth(async function (context) {
...
return {
props: { user: context.req.session.user, ... },
};
});
Upvotes: 2
Reputation: 35271
I think you can redirect from the server.
import { withIronSession } from "next-iron-session";
const user_home = (props) => {
// ...some other layout stuff
};
export const getServerSideProps = withIronSession(
async ({ req, res }) => {
const user = req.session.get("user");
if (!user) {
redirect: {
permanent: false,
destination: "/login",
},
}
return {
props: { user: user },
};
},
{
cookieName: "NEXT_EXAMPLE",
cookieOptions: {
secure: true,
},
password: process.env.APPLICATION_SECRET,
}
);
export default user_home;
Upvotes: 0