npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@alpakaslab/nextjs-jwt-auth

v0.1.0

Published

NextJs JWT Auth is a library designed for the Next.js 14 ecosystem, aiming to simplify and make JWT authentication more accessible. It is particularly focused on clients who already have a backend with authenticated credentials. Based on the [next-auth](h

Downloads

141

Readme

⭐️ About

NextJs JWT Auth is a library designed for the Next.js 14 ecosystem, aiming to simplify and make JWT authentication more accessible. It is particularly focused on clients who already have a backend with authenticated credentials. Based on the next-auth library.

🚀 Getting Started

Install using an package manager

pnpm add @alpakaslab/nextjs-jwt-auth
# or
yarn add @alpakaslab/nextjs-jwt-auth
# or
npm install @alpakaslab/nextjs-jwt-auth

🧩 Initialization

First, create an API route with the path /api/auth/route.ts and generate API routes using the getApiRoutes() helper.

// api/auth/route.ts
import { getApiRoutes } from '@alpakaslab/nextjs-jwt-auth'

const { DELETE, POST } = getApiRoutes<{ email: string; password: string }>({
    callbacks: {
        async signIn(credentials) {
            // Your login logic
            const user = getUser(credentials)

            // If the login is correct, return an object in JWT format
            return {...}

            // If the credentials are wrong return null
            return null
        }
    }
})

export { DELETE, POST }

Second, create an middleware file /middleware.ts and generate the handler using the getMiddleware() helper.

// middleware.ts
import { getMiddleware } from '@alpakaslab/nextjs-jwt-auth'

export const middleware = getMiddleware(undefined, async (request, payload) => {
    // Refresh token logic
   if(payload.experisIn > new Date()){
        const newData = await refreshToken(payload.refreshToken)

        // If the new data is correct, return an object in JWT format to update the cookie
        if(newData){
            return {...}
        }

        // If the refresh method returns an error, return null to force user signout
        return null
   }

    // If you don't need to update the token and the user is okay, return true
    return true
})

// Configure only the routes that require authentication
export const config = {
    matcher: '/admin/:path*'
}

And create two enviroment variables

AUTH_URL="application base url"
AUTH_SECRET="generated token to encrypt the jwt"

🪄 Using the library

getSession() - This server side function returns the user session or null when user is not authenticated

import { getSession } from '@alpakaslab/nextjs-jwt-auth'
import { redirect } from 'next/navigation'

export default async function Page() {
    const session = await getSession()

    if (!session) redirect('/')

    return <div>{session.name}</div>
}

signIn() - This client side helper function receives the user credentials as a parameter and call the sign in api route, and return true or false if user is authenticated

import { signIn } from '@alpakaslab/nextjs-jwt-auth'

const onSubmit = async data => {
    const authenticated = await signIn({
        email: data.email,
        password: data.password
    })

    if (authenticated) {
        // signIn success logic
        router.replace('/admin/')
    } else {
        // signIn failed logic
    }
}

signOut() - This client side helper function call the sign out api route and return true or false if user is correctly signout

import { signOut } from '@alpakaslab/nextjs-jwt-auth'

const onClick = async () => {
    const success = await signOut()

    if (success) {
        // signOut success logic
        router.replace('/')
        router.refresh()
    } else {
        // signOut failed logic
    }
}

💎 Typescript

All functions and methods are type-safe, and if you need to modify the JWT object, just overwrite it with a .d.ts file.

// nextjs-jwt-auth.d.ts
import { JWT, DefaultJWT } from '@alpakaslab/nextjs-jwt-auth'

declare module '@alpakaslab/nextjs-jwt-auth' {
    interface JWT extends DefaultJWT {
        accessToken: string
        refreshToken: string
        experisIn: number
        role: string
    }
}