Coder Social home page Coder Social logo

korizki / iron-session-project Goto Github PK

View Code? Open in Web Editor NEW
0.0 1.0 0.0 40 KB

Project web menggunakan framework Next.js dan additional library session management Iron Session.

Home Page: https://iron-session-project.vercel.app

JavaScript 9.38% TypeScript 83.25% CSS 7.37%

iron-session-project's Introduction

This is a Next.js project, with Session Management using iron-session.

Step by Step

  1. Prepare a Next.js Project or you can use your existing Next.js project

  2. Create a session configuration, by creating new file on root-project-folder/lib/config/session-config.js

export const ironOptions = {
   cookieName: "your_app_session",
   password: "thisisyourpasswordwithminlength32char",
   cookieOptions: {
      # if your production page using https, set this to true.
      secure: false,
      maxAge: 150
   }
}
  1. Create a wrapper function, we will using this function when interact with session. This file may created at root-project-folder/lib/config/useSession.js
import { withIronSessionApiRoute, withIronSessionSsr } from 'iron-session/next'
import { sessionConfig } from "./session-config"

export function withSessionRoute(handler) {
   return withIronSessionApiRoute(handler, sessionConfig)
}

export function withSessionSsr(handler) {
   return withIronSessionSsr(handler, sessionConfig)
}
  1. Create an api handle our request to create (on Log In) or delete (on Log Out) session. First create new file handling log in process on root-project-folder/pages/api/login.ts
import { NextApiResponse } from "next"
import { withSessionRoute } from '../../lib/config/useSession'

interface RequestBody {
   email: string,
   name: string
}
interface NextApiRequest {
   body: string,
   user: object,
   method: string,
   session: any
}

export default withSessionRoute(login)

async function login(req: NextApiRequest, res: NextApiResponse) {
   if (req.method == 'POST') {
      const userInfo: RequestBody = JSON.parse(req.body)
      req.session.user = userInfo
      await req.session.save()
      res.send(
         {
            status: 'ok',
            message: "Successfully adding new session",
            sessionInfo: userInfo
         }
      )
   } else {
      res.send({
         status: 'failed',
         message: 'no route available'
      })
   }
}
  1. Then we create a new file on existing folder for handling log out process (clear session) root-project-folder/pages/api/logout.ts
import { withSessionRoute } from "@/lib/config/useSession";
import { NextApiRequest, NextApiResponse } from "next";

export default withSessionRoute(logout)

async function logout(req: NextApiRequest, res: NextApiResponse) {
   req.session.destroy()
   res.send({ status: 'ok', message: 'Successfully clear session' })
}
  1. Now on login form we need to add this process
const handleLogin = async (e: React.SyntheticEvent, email: string, name: string) => {
   e.preventDefault()
   const body = { email, name }
   const response = await fetch("/api/login", {
      method: "POST",
      body: JSON.stringify(body),
      headers: { "Content-Type": "application-json" }
   })
   if (response.ok) {
      sessionStorage.setItem('session', '')
      # your code like ==> router.push("/home") to redirect to homepage
   }
}
  1. For getting the value on saved session, example in home page, we can adding this process
export const getServerSideProps = withSessionSsr(
   async ({ req, res }: any) => {
      if (req.session.user) {
         const user = req.session.user
         return {
            props: { user }
         }
      } else {
         return {
            props: { user: null }
         }
      }
   }
)

#then pass the value on props
export default function Home(props: PropsUser) {
   # your code ...
}

iron-session-project's People

Contributors

korizki avatar

Watchers

 avatar

iron-session-project's Issues

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.