Coder Social home page Coder Social logo

ghostlexly-auth's Introduction

✨ ghostlexly-auth ✨

The best, tiny, robust, customizable, and easy authentication for Next.js + Express.js stack.

Features

  • 🐣 - Easy to use
  • 📝 - Login & Logout
  • 🔒 - JWT Secured Cookie
  • 💅 - Maintain user session and access user session data
  • 🤖 - Fetch module with Axios included (with authorization header)
  • 💻 - SSR ready
  • 🔥 - Battle-tested on 100k/user websites
  • 🔑 - Compatible with PassportJS and Auth0
  • ✅ - Module written in TypeScript

Installation

Install package

yarn add ghostlexly-auth

Add Context provider to your application

We need to wrap our application with the ghostlexly-auth context provider so that we can fetch user data within our application.

Add the context provider inside your _app.tsx file.

Example

// /pages/_app.tsx

import { GhostlexlyAuthProvider } from "ghostlexly-auth";

function MyApp({ Component, pageProps, router }) {
  return (
    <GhostlexlyAuthProvider {...pageProps}>
      <Component {...pageProps} />
    </GhostlexlyAuthProvider>
  );
}

export default MyApp;

You can configure the provider like you wish

<GhostlexlyAuthProvider {...pageProps} userDataUrl="/api/me" cookieExpireInDays="7">
  <Component {...pageProps} />
</GhostlexlyAuthProvider>

GhostLexlyAuthProvider options:

  • userDataUrl: The URL path to your API from which we will fetch the user's session data that we can later access using auth.session.
  • cookieExpireInDays: Cookie's expiration time in number of days. (31 by default)

Login the user

We first need to declare a auth variable with the useAuth hook. Then, we can call signIn() method to login the user.

Important: The signIn() method requires your api endpoint to return access_token in the response. This token will be used later in a Authorization header, while fetching user data.

Example

import { useAuth } from "ghostlexly-auth";

export default function LoginPage() {
  const router = useRouter();
  const auth = useAuth(); // 👈 here

  const onSubmit = async (data) => {
    auth
      .signIn("/api/login", { email: data.email, password: data.password })
      .then((res) => {
        router.push("/member-area/"); // 👈 redirect to this path if the login is successful
      })
      .catch((err) => {
        alert("Invalid user infos !"); // 👈 return an error if the credentials are invalid
      });
  };
}

Example api endpoint response

The api endpoint return a JWT Token that will be used later on Authorization header.

// https://localhost/api/login
{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE2ODkxMTExNDYsImV4cCI6MTY4OTcxNTk0Nn0.-ELIPUuYVfPOL3wXe-yCIU-TsSXUS4DXBuzirfdfTOg"
}

The signIn() method returns a promise. It resolves to the user's session data if the login is successful. If the API does not return a 200 response, it will return an error.

You can provide two parameters to the signIn method:

  • url: The path of the API to call for the login.
  • data: The data to be sent to the API.

Logout the user

We first need to declare a auth variable with the useAuth hook. Then, we can call signOut() method to logout the user.

Example

import { useAuth } from "ghostlexly-auth";

export default function LogoutPage() {
  const auth = useAuth();
  auth.signOut({ redirectUrl: "/member-area/login" });
}

The signOut() method remove the user's cookie and redirect to a path.

You can provide one parameter to the signOut() method:

  • redirectUrl: The path to redirect the user to.

Get user session

The session object in useAuth hook is the easiest way to check if someone is signed in and get his data.

We first need to declare a auth variable with the useAuth hook. Then, we can call session object to access the user session.

Example

import { useAuth } from "ghostlexly-auth";

export default function ExamplePage() {
  const auth = useAuth();

  console.log(auth.session.status); // 👈 user's session status (if the user is logged in or not)
  console.log(auth.session.data); // 👈 access user session data

  return (
    <div>
      {auth.session.status === "authenticated" && <h1>I'm logged in !</h1>}

      {auth.session.status === "unauthenticated" && <h1>I'm not logged in.</h1>}
    </div>
  );
}

auth.session returns an object containing two values: data and status:

  • data: This can be two values: Session / null.
    • when the session hasn't been fetched yet, data will be null
    • in case of success, data will be Session.
  • status: Enum mapping to two possible session states: "authenticated" | "unauthenticated"

Retrieve user's Access Token

Client side:

import { getAccessToken } from "ghostlexly-auth";

export default TestPage() {
    const accessToken = getAccessToken();
    console.log(accessToken);
}

Server side:

import { getAccessToken } from "ghostlexly-auth";

export async function getServerSideProps({ req }) {
  const accessToken = getAccessToken(req);
  console.log(accessToken);
}

Call the api with the Authorization header and Axios

This request will automatically include an Authorization header with your access token.

The api() method accepts a req parameter for the SSR.

import { api } from "ghostlexly-auth";

export default TestPage() {
    const onSubmit = () => {
        api().get("https://dummyjson.com/products");

        api().post("/api/register", { email: "[email protected]"});
    }
}

More informations on Axios

ghostlexly-auth's People

Contributors

ghostlexly avatar

Stargazers

Avitus Ibrahim avatar souvik dutta avatar Tushar avatar Denny Harijanto avatar Prakrit M. avatar Mahdi Chaari avatar Bryce Eppler avatar Andrey Bukati avatar Victor Argote avatar Dennis Li avatar  avatar Hải Nguyễn avatar Déric Marchand avatar Rohan avatar Boubouh Karim avatar  avatar Kutsan Kaplan avatar NightKunGz avatar  avatar Pedro H Jalowitzki avatar Karim Boubouh avatar  avatar

Watchers

 avatar Pedro H Jalowitzki avatar

ghostlexly-auth's Issues

Auth with App folder

Hey, i found your post on reddit where you were trying to create a next app with express/passport backend and just saw that you created your own lib.
But could you tell how could i implement this with Nextjs 13 App Folder?
I'm relatively new to Nextjs and web dev in general so i'm a little lost, how should i be creating the AuthProvider, etc, thx

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.