Code Monkey home page Code Monkey logo

nextjs-postgres-auth-starter's Introduction

Next.js + PostgreSQL Auth Starter

This is a Next.js starter kit that uses NextAuth.js for simple email + password login, Drizzle as the ORM, and a Neon Postgres database to persist the data.

Deploy Your Own

You can clone & deploy it to Vercel with one click:

Deploy with Vercel

Developing Locally

You can clone & create this repo with the following command

npx create-next-app nextjs-typescript-starter --example "https://github.com/vercel/nextjs-postgres-auth-starter"

Getting Started

First, run the development server:

pnpm dev

Open http://localhost:3000 with your browser to see the result.

Learn More

To learn more about Next.js, take a look at the following resources:

You can check out the Next.js GitHub repository - your feedback and contributions are welcome!

nextjs-postgres-auth-starter's People

Contributors

balazsorban44 avatar erasta avatar heychazza avatar hjaber avatar leerob avatar steven-tey avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

nextjs-postgres-auth-starter's Issues

env values documentation

Hi,

I had recently cloned the auth starter before the .evn.example was updated again. Before there were only two values

POSTGRES_URL and NEXTAUTH_SECRET

Which worked, but now it's looking for other things, not sure what changed everywhere. Can you please update the readme to show us how to setup up the .env for this to work properly. Thanks

Install error on Vercel fresh install

Just tried to install this repo as a new project, and it failed on the first step (on the web interface):

Build failed with 3 errors:
19:44:49.842 | vc-file-system:node_modules/uuid/dist/esm-node/md5.js:1:19: ERROR: Could not resolve "crypto"
19:44:49.842 | vc-file-system:node_modules/uuid/dist/esm-node/rng.js:1:19: ERROR: Could not resolve "crypto"
19:44:49.842 | vc-file-system:node_modules/uuid/dist/esm-node/sha1.js:1:19: ERROR: Could not resolve "crypto"

general_view

deploy_fail--

And less critical, but worth to consider warning:
warning

Next Auth ([...nextauth] route.ts) Doesn't work on Localhost

The sign-up works but the sign-in doesn't on Localhost. Both sign-in and sign-up work on Vercel's hosted version.
The project was created using the one-click deployment to Vercel on Jun 23, 2023.

The message "Signed in as X" appears but the three dot loading state over the Sign In button does not end and the page gets stuck before getting to /protected.

I get this error - error TypeError [ERR_INVALID_URL]: Invalid URL. Am I unable to reach /protected despite being signed in because localhost is not an https route, whereas the Vercel deployed version is? http://localhost:3000/

NextJS 13 App Dir NextAuth Prisma Error - [next-auth][error][CLIENT_FETCH_ERROR] & [MISSING_ADAPTER_METHODS_ERROR]

I am using a Prisma adapter with a Supabase Postgres connection, I am unsure of what's going. I connected a SendGrid server for custom emails.

export const authOptions: NextAuthOptions = {
  adapter: PrismaAdapter(prisma as any),
  session: {
    strategy: 'jwt',
  },
  providers: [
    EmailProvider({
      server: {
        host: HOST,
        port: PORT,
        auth: {
          user: USER,
          pass: PASSWORD,
        },
      },
      from: FROM,
    }),
  ],

  callbacks: {
    session: ({ session, token }) => {
      console.log('Session Callback', { session, token });
      return {
        ...session,
        user: {
          ...session.user,
          id: token.id,
          randomKey: token.randomKey,
        },
      };
    },
    jwt: ({ token, user }) => {
      console.log('JWT Callback', { token, user });
      if (user) {
        const u = user as unknown as any;
        return {
          ...token,
          id: u.id,
          randomKey: u.randomKey,
        };
      }
      return token;
    },
  },
};

const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };
[next-auth][error][MISSING_ADAPTER_METHODS_ERROR] 
https://next-auth.js.org/errors#missing_adapter_methods_error Required adapter methods were missing: createVerificationToken, useVerificationToken, getUserByEmail MissingAdapterMethods [MissingAdapterMethodsError]: Required adapter methods were missing: createVerificationToken, useVerificationToken, getUserByEmail
    at assertConfig (webpack-internal:///(sc_server)/./node_modules/next-auth/core/lib/assert.js:71:20)
    at AuthHandler (webpack-internal:///(sc_server)/./node_modules/next-auth/core/index.js:90:54)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async NextAuthRouteHandler (webpack-internal:///(sc_server)/./node_modules/next-auth/next/index.js:49:30)
    at async NextAuth._args$ (webpack-internal:///(sc_server)/./node_modules/next-auth/next/index.js:83:24)
    at async eval (webpack-internal:///(sc_server)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:265:37) {
  code: 'MISSING_ADAPTER_METHODS_ERROR'
}


This is my Prisma schema:

datasource db {
    provider  = "postgresql"
    url       = env("DATABASE_URL")
    directUrl = env("DIRECT_URL")
}

generator client {
    provider = "prisma-client-js"
}

model Account {
    id                String  @id @default(cuid())
    userId            String
    type              String
    provider          String
    providerAccountId String
    refresh_token     String? @db.Text
    access_token      String? @db.Text
    expires_at        Int?
    token_type        String?
    scope             String?
    id_token          String? @db.Text
    session_state     String?

    user User @relation(fields: [userId], references: [id], onDelete: Cascade)

    @@unique([provider, providerAccountId])
}

model Session {
    id           String   @id @default(cuid())
    sessionToken String   @unique
    userId       String
    expires      DateTime
    user         User     @relation(fields: [userId], references: [id], onDelete: Cascade)
}

model User {
    id            String    @id @default(cuid())
    name          String?
    email         String?   @unique
    emailVerified DateTime?
    image         String?
    accounts      Account[]
    sessions      Session[]
}

model VerificationToken {
    identifier String
    token      String   @unique
    expires    DateTime

    @@unique([identifier, token])
}

My prisma.ts file:

import { PrismaClient } from '@prisma/client';

// PrismaClient is attached to the `global` object in development to prevent
// exhausting your database connection limit.
//
// Learn more:
// https://pris.ly/d/help/next-js-best-practices

const globalForPrisma = global as unknown as { prisma: PrismaClient };

export const prisma =
  globalForPrisma.prisma ||
  new PrismaClient({
    log: ['query'],
  });

if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma;

Invalid Compact JWE

Hey, after cloning and following the installation instructions i get this error (sorry for the long stacktrace but hope it helps):

[next-auth][error][JWT_SESSION_ERROR] 
https://next-auth.js.org/errors#jwt_session_error Invalid Compact JWE {
 message: 'Invalid Compact JWE',
 stack: 'JWEInvalid: Invalid Compact JWE\n' +
   '    at compactDecrypt (webpack-internal:///(sc_server)/./node_modules/jose/dist/node/cjs/jwe/compact/decrypt.js:18:15)\n' +  
   '    at jwtDecrypt (webpack-internal:///(sc_server)/./node_modules/jose/dist/node/cjs/jwt/decrypt.js:10:61)\n' +
   '    at Object.decode (webpack-internal:///(sc_server)/./node_modules/next-auth/jwt/index.js:44:52)\n' +
   '    at async Object.session (webpack-internal:///(sc_server)/./node_modules/next-auth/core/routes/session.js:25:34)\n' +     
   '    at async AuthHandler (webpack-internal:///(sc_server)/./node_modules/next-auth/core/index.js:161:37)\n' +
   '    at async getServerSession (webpack-internal:///(sc_server)/./node_modules/next-auth/next/index.js:129:21)\n' +
   '    at async unstable_getServerSession (webpack-internal:///(sc_server)/./node_modules/next-auth/next/index.js:155:12)\n' +  
   '    at async AuthStatus (webpack-internal:///(sc_server)/./components/auth-status.tsx:11:21)',
 name: 'JWEInvalid'
}

Generated one here: https://generate-secret.vercel.app/32 (only required for localhost)

env.local

...
NEXTAUTH_SECRET=f6327cf5edcce9bb2def2dd44c13ac7c
NEXTAUTH_URL=http://localhost:3000 # and tried with http://localhost:3000/api/auth

[...nextauth].ts (route)

import GoogleProvider from "next-auth/providers/google";
import NextAuth from "next-auth";
import { PrismaAdapter } from "@auth/prisma-adapter";
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

const handler = NextAuth({
  adapter: PrismaAdapter(prisma),
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
  ],
});

export { handler as GET, handler as POST };

Thanks in advance for guiding me to a solution!

registration is working, login isnt.

I cloned the repo and connected to a local mysql instance.

I am able to register an email/password (with data being updated in database), but when trying to login, I keep getting a 307 redirect back to the login page.

What am I missing?

TIA

Just a Question (No Issue)

Hi Guys,

Pardon my incompetence here, I am relearning Next (used it once three years ago)... Just wondering how the redirect happens (and where the code is) for /protected when not logged in.

I saw the getServerSession, will try tracing from there... Thanks

Build is failing due to error in middleware.ts

Thanks for the great sample project. I've been able to implement all of the code in the project, but my build is failing due to an issue I'm seeing in middleware.ts:

The Edge Function "middleware" is referencing unsupported modules: - __vc__ns__/0/middleware.js: app/auth.config

My middleware.ts and auth.config.ts are exactly the same as those in the project. I don't know what else I can do here. Please advise. Thanks.

Fresh install - Hydration Error

Hey Steven,

Thank you so much for adding this example so quickly after the tweet, this will help many others including myself with auth scaffolding (and learning from it).

I've done a fresh install, created my .env, added my credentials and ran yarn dev but get the following error.

Not sure if I've missed anything else.
CleanShot 2022-11-27 at 9 17 07@2x

Demo Error

I received this error while registering and signing into the demo application.

Failed to load resource: the server responded with a status of 500 ()

Error: An error occurred in the Server Components render. The specific message is omitted in production builds to avoid leaking sensitive details. A digest property is included on this error instance which may provide additional details about the nature of the error.

Can i contribute to this repo?

I want to make PR with a change about removing ts-ignore comment but I get access denied when i try to push a branch. 😃

Hydration error when using Keeper password manager chrome extension

Hi,

I'm having some issues with a fresh install when using the Keeper password manager chrome extension.

Error: Unhandled Runtime Error
Error: Hydration failed because the initial UI does not match what was rendered on the server.

This extension adds some attributes to the markup, in particular to the login/register forms. After some debugging, I noticed that when disabling the extension, the error no longer shows up. The attribute added to the inputs is: data-keeper-lock-id="...".

The error makes sense somewhat, but still feels like a bug.

Please let me know if there is something that can be done about this. For now, I will just develop with the extension turned off, but I wonder if this would happen when deploying the app as well.

All the best.

PostgresError: relation "User" does not exist

I created a new project using this as the template but ran into an issue when creating a new user. It throws the error PostgresError: relation "User" does not exist. I've tried different variants of environmental variable files but none of them work:

  • .env
  • .env.local
  • .env.development.local

My understanding is that it should be generating the User table on first user creation but it doesn't?

I've referenced the documentation here to no success:
https://vercel.com/docs/storage/vercel-postgres/quickstart

Am I missing something?

next dev --turbo

   ▲ Next.js 14.0.4 (turbo)
   - Local:        http://localhost:3000
   - Environments: .env.development.local

 ✓ Ready in 858ms
 ○ Compiling /register ...
 ✓ Compiled /register in 1061ms
 ✓ Compiled /favicon.ico in 80ms
   Reload env: .env.local
 ⨯ node_modules/.pnpm/[email protected]/node_modules/postgres/src/connection.js (794:18) @ ErrorResponse
 ⨯ PostgresError: relation "User" does not exist
    at ErrorResponse (/Users/michaelzavattaro/Developer/Github/chronopass-ai/.next/server/chunks/node_modules_34cec9._.js:2844:224)
    at handle (/Users/michaelzavattaro/Developer/Github/chronopass-ai/.next/server/chunks/node_modules_34cec9._.js:2644:728)
    at TLSSocket.data (/Users/michaelzavattaro/Developer/Github/chronopass-ai/.next/server/chunks/node_modules_34cec9._.js:2530:17)
    at TLSSocket.emit (node:events:519:28)
null
   Reload env: .env
 ⨯ node_modules/.pnpm/[email protected]/node_modules/postgres/src/connection.js (794:18) @ ErrorResponse
 ⨯ PostgresError: relation "User" does not exist
    at ErrorResponse (/Users/michaelzavattaro/Developer/Github/chronopass-ai/.next/server/chunks/node_modules_34cec9._.js:2844:224)
    at handle (/Users/michaelzavattaro/Developer/Github/chronopass-ai/.next/server/chunks/node_modules_34cec9._.js:2644:728)
    at TLSSocket.data (/Users/michaelzavattaro/Developer/Github/chronopass-ai/.next/server/chunks/node_modules_34cec9._.js:2530:17)
    at TLSSocket.emit (node:events:519:28)
null

TypeError on fresh install

I've just cloned the repo and did this:

npm install
npx prisma db push
npm run dev

The main page showed up for a split second before this error got displayed:

image

Here's the full error text:

Unhandled Runtime Error
TypeError: Cannot read properties of undefined (reading 'call')

Call Stack
options.factory
file:///D:/Workspace/tmp/nextjs-mysql-auth-starter/.next/static/chunks/webpack.js (710:31)
__webpack_require__
/_next/static/chunks/webpack.js (37:33)
fn
file:///D:/Workspace/tmp/nextjs-mysql-auth-starter/.next/static/chunks/webpack.js (365:21)
require
node_modules\next\dist\client\image.js (7:15)
./node_modules/next/dist/client/image.js
file:///D:/Workspace/tmp/nextjs-mysql-auth-starter/.next/static/chunks/app/page.js (50:1)
options.factory
/_next/static/chunks/webpack.js (710:31)
__webpack_require__
file:///D:/Workspace/tmp/nextjs-mysql-auth-starter/.next/static/chunks/webpack.js (37:33)
fn
/_next/static/chunks/webpack.js (365:21)
__webpack_require__
node_modules\next\dist\client\app-index.js (26:16)
requireModule
node_modules\next\dist\compiled\react-server-dom-webpack\client.js (142:0)
initializeModuleChunk
node_modules\next\dist\compiled\react-server-dom-webpack\client.js (427:0)
readChunk
node_modules\next\dist\compiled\react-server-dom-webpack\client.js (252:0)
mountLazyComponent
node_modules\next\dist\compiled\react-dom\cjs\react-dom.development.js (23079:0)
beginWork
node_modules\next\dist\compiled\react-dom\cjs\react-dom.development.js (24792:0)
beginWork$1
node_modules\next\dist\compiled\react-dom\cjs\react-dom.development.js (32185:0)
performUnitOfWork
node_modules\next\dist\compiled\react-dom\cjs\react-dom.development.js (31082:0)
workLoopSync
node_modules\next\dist\compiled\react-dom\cjs\react-dom.development.js (30891:0)
renderRootSync
node_modules\next\dist\compiled\react-dom\cjs\react-dom.development.js (30856:0)
recoverFromConcurrentError
node_modules\next\dist\compiled\react-dom\cjs\react-dom.development.js (30109:0)
performConcurrentWorkOnRoot
node_modules\next\dist\compiled\react-dom\cjs\react-dom.development.js (29996:0)
workLoop
node_modules\next\dist\compiled\scheduler\index.js (10:3921)
flushWork
node_modules\next\dist\compiled\scheduler\index.js (10:3629)
MessagePort.performWorkUntilDeadline
node_modules\next\dist\compiled\scheduler\index.js (10:1811)

Here's the server log:

...
event - compiled client and server successfully in 3.2s (658 modules)
[next-auth][warn][EXPERIMENTAL_API]
`unstable_getServerSession` is experimental and may be removed or changed in the future, as the name suggested.
https://next-auth.js.org/configuration/nextjs#unstable_getServerSession}
https://next-auth.js.org/warnings#EXPERIMENTAL_API
[next-auth][warn][EXPERIMENTAL_API]
`unstable_getServerSession` is used in a React Server Component.
https://next-auth.js.org/configuration/nextjs#unstable_getServerSession}
https://next-auth.js.org/warnings#EXPERIMENTAL_API
[next-auth][warn][NEXTAUTH_URL]
https://next-auth.js.org/warnings#nextauth_url

Environment info:

  • OS: Windows 11
  • Node: v18.12.1

But if I run the build and do npm run start, it works without an issue 🤔

Session data not being displayed on initial login?

Hello! Just a quick question. I have the same "issue" as the example at: https://nextjs-mysql-auth.vercel.app/

Is there a reason why, when after successful login, that the session data doesn't show at the top of the page?

For me, it does not display once logged in, initially. But if I refresh the page after I am logged in, it shows up.

Is this by design or am I missing something?

Thanks!

Issues utilizing "Use Client" "useEffect" etc.

Hello,
I am currently facing an issue with migration, i made a small app to act as a suggestion, tip or feature "jar" but just now wanted to add auth, however my app utilizes "use client" "useState" and "useEffect" however each time i use any of these, i immediately get errors from postgressql (is what i assume) but the actual error points to FS for some reason.

This only happens on pages that are actively being "protected" how do i avoid encountering this issue whilst still maintaining the features of my application?

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.