NextAuth.js plugin for Fastify.

Overview

fastify-next-auth

Authentication plugin for Fastify, powered by NextAuth.js.

Requirements:

Installation

npm install next-auth @fastify/cookie @fastify/formbody fastify-next-auth

Usage

import fastify from 'fastify'
import cookie from '@fastify/cookie'
import formBody from '@fastify/formbody'
import AppleProvider from 'next-auth/providers/apple'
import GoogleProvider from 'next-auth/providers/google'
import EmailProvider from 'next-auth/providers/email'
import type { NextAuthOptions } from 'fastify-next-auth'
import NextAuth from 'fastify-next-auth'

const app = fastify()

app
  .register(cookie)
  .register(formBody)
  .register(NextAuth, {
    secret: process.env.NEXTAUTH_SECRET,
    providers: [
    // OAuth authentication providers
      AppleProvider({
        clientId: process.env.APPLE_ID,
        clientSecret: process.env.APPLE_SECRET,
      }),
      GoogleProvider({
        clientId: process.env.GOOGLE_ID,
        clientSecret: process.env.GOOGLE_SECRET,
      }),
      // Sign in with passwordless email link
      EmailProvider({
        server: process.env.MAIL_SERVER,
        from: '<[email protected]>',
      }),
    ],
  } as NextAuthOptions)

Client API

The client library makes it easy to interact with sessions from your frontend.

Example Session Object

{
  user: {
    name: string
    email: string
    image: string
  },
  expires: Date // This is the expiry of the session, not any of the tokens within the session
}

Server Side Example

import {
  getCsrfToken,
  getProviders,
  getSession
} from 'fastify-next-auth/client'

fastify.get('/api/info', async (req, reply) => {
  const session = await getSession({ req })
  const token = await getCsrfToken({ req })
  // Unlike getSession() and getCsrfToken(), when calling getProviders() server side,
  // you don't need to pass anything, just as calling it client side.
  const providers = await getProviders()
  return {
    session,
    providers,
    token
  }
})

Client Side Example

import {
  getCsrfToken,
  getProviders,
  getSession,
  signIn,
  signOut
} from 'fastify-next-auth/client'

async function myFunction() {
  const session = await getSession()
  const providers = await getProviders()
  const token = await getCsrfToken()

  // Redirects to sign in page
  signIn()

  // Starts OAuth sign-in flow
  signIn('google')

  // Starts Email sign-in flow
  signIn('email', { email: '[email protected]' })

  signOut()
}

For more info on client side usage, proceed to the NextAuth.js Client API docs page.

License

MIT

You might also like...

Api simples de OCR feita com Fastify e Tesseract.js

ocr-api API de OCR simples feita com Fastify e Tesseract.js Iniciando Depois de instalar as depedências, simplesmente inicia com npm run start. Nota:

Oct 8, 2022

Babel-plugin-amd-checker - Module format checking plugin for Babel usable in both Node.js the web browser environments.

babel-plugin-amd-checker A Babel plugin to check the format of your modules when compiling your code using Babel. This plugin allows you to abort the

Jan 6, 2022

A variety of jQuery plugin patterns for jump starting your plugin development

jQuery Plugin Patterns So, you've tried out jQuery Boilerplate or written a few of your own plugins before. They work to a degree and are readable, bu

Dec 31, 2022

A tool to get plugin statistics of Obsidian plugin ecosystem.

A tool to get plugin statistics of Obsidian plugin ecosystem.

Obsidian Plugin Stats A tool to get plugin statistics of Obsidian plugin ecosystem. Usage You can use this tool to see the plugins that has hit commun

Dec 25, 2022

📦 Alpine JS plugin to extend the functionality of the official $persist plugin

Alpine JS Persist Extended Alpine JS magic method $storage extends the official $persist plugin to help you work with local storage 📦 Example 👀 div

Dec 28, 2022

kakaolink-plugin is a remote-kakao plugin for sending KakaoLinks instead of plain text

kakaolink-plugin is a remote-kakao plugin for sending KakaoLinks instead of plain text

kakaolink-plugin Discord Server About kakaolink-plugin is a remote-kakao plugin for sending KakaoLinks instead of plain text. Requirements Node.js v17

Oct 1, 2022

A markdown-it plugin that process images through the eleventy-img plugin. Can be used in any projects that uses markdown-it.

markdown-it-eleventy-img A markdown-it plugin that process images through the eleventy-img plugin. Can be used in any projects that use markdown-it. F

Dec 20, 2022

This is a simple Image popup Jquery plugin. With a very simple configuration, you can show a popup on your webpage. By the way, this plugin works after page load.

This is a simple Image popup Jquery plugin. With a very simple configuration, you can show a popup on your webpage. By the way, this plugin works after page load.

Jquery-SingleImagePopup This is a simple Image popup Jquery plugin. With a very simple configuration, you can show a popup on your webpage. By the way

Aug 22, 2022

An obsidian toolbar plugin, modified from the Cmenu plugin

An obsidian toolbar plugin, modified from the Cmenu plugin

obsidian-editing-toolbar Plugin Thanks to the cmenu plugin, which gave me a lot of inspiration, but this plugin has not been maintained for more than

Dec 29, 2022
Comments
  • Implementation when Client and Backend belong to different domains

    Implementation when Client and Backend belong to different domains

    Hi! Thank you for this library! You have done an amazing job! Could you please answer a doubt of mine? Is it possible to implement this auth aproach when frontend and backend are being hosted on different domains? Do I need to install this library on both sides and define NEXTAUTH_URL to the backend domain? How should I deal with CORS? Can I just make simple API calls to nextauth rest API? For example: "/api/auth/signin"

    opened by Elsoberanold 0
Releases(v0.2.4)
Owner
Robert Soriano
[object Object]
Robert Soriano
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
Next.js + Tailwind + Typescript + Prisma + NextAuth starter project

This is a Next.js project bootstrapped with create-next-app. Getting Started First, run the development server: npm run dev # or yarn dev Open http://

Steven Tey 106 Jan 3, 2023
A simple JS example for NextAuth Google login with a popup window instead of redirect.

A simple JS example for NextAuth Google login with a popup window instead of redirect.

null 13 Dec 7, 2022
API server for AospExtended made with Fastify.

AospExtended API API server for AospExtended made with Fastify. Run Locally Clone the project git clone https://github.com/allstargaurav/aospextende

Gaurav 3 Oct 12, 2022
Run REST APIs in Node.js applications frameworks (Express, Koa, Hapi and Fastify) on top of any Serverless Cloud.

?? Serverless Adapter Install | Usage | Support | Architecture | Credits Run REST APIs and other web applications using your existing Node.js applicat

Vinicius Lourenço 45 Jan 1, 2023
🚀 Blazing Fast S3 Powered CDN ✨ Powered By Fastify, S3 Buckets & Docker!

?? WasiCDN Blazing Fast S3 Powered CDN, Powered By Fastify, S3 Compatible Buckets & Docker! Core DockerHub: https://hub.docker.com/r/maximking19/wasic

Maxim 5 Aug 31, 2022
🔥 Blazing Fast API which scrapes Mydramalist.com made using Fastify and Cheerio.

mydramalist API ?? Blazing Fast API which scrapes Mydramalist.com made using Fastify and Cheerio. Setup pnpm install node index.js available at http:/

Paranjay Singh 6 Dec 4, 2022
Ergonomic, chaining-based Typescript framework for quick API development for Fastify

Ergonomic, chaining-based Typescript framework for quick API development for Fastify Installation > pnpm add @t3ned/channel Usage // index.ts import

T3NED 6 Aug 2, 2022
End-to-End type safety for REST APIs written in Fastify. Only problem is you have to explicity export and register route handlers. LOL

Chino intelligence in japaneese End-to-End type safety for REST APIs written in Fastify. Only problem is you have to explicity export and register rou

sambit sahoo 2 Sep 12, 2022