PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, September 4, 2022

[FIXED] How can I implement authentication with next-iron-session using getServerSideProps without including the same code on each page

 September 04, 2022     authentication, javascript, next.js, node.js, reactjs     No comments   

Issue

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;

Solution

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, ... },
  };
});


Answered By - J.dev
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing