Coder Social home page Coder Social logo

adrianhajdin / project_next_14_ai_prompt_sharing Goto Github PK

View Code? Open in Web Editor NEW
2.5K 8.0 375.0 51 KB

Next.js recently became the official React framework as outlined in React docs. In this course, you'll learn the most important Next.js concepts and how they fit into the React ecosystem. Finally, you'll put your skills to the test by building a modern full-stack Next 14 application.

Home Page: https://www.jsmastery.pro/ultimate-next-course

JavaScript 84.39% CSS 15.61%
nextjs next14 nextjs14

project_next_14_ai_prompt_sharing's Introduction


Project Banner
Next.js mongodb tailwindcss

Next.js 14 AI Prompt Sharing Application

Build this project step by step with our detailed tutorial on JavaScript Mastery YouTube. Join the JSM family!
  1. πŸ€– Introduction
  2. βš™οΈ Tech Stack
  3. πŸ”‹ Features
  4. 🀸 Quick Start
  5. πŸ•ΈοΈ Snippets
  6. πŸ”— Links
  7. πŸš€ More

🚨 Tutorial

This repository contains the code corresponding to an in-depth tutorial available on our YouTube channel, JavaScript Mastery.

If you prefer visual learning, this is the perfect resource for you. Follow our tutorial to learn how to build projects like these step-by-step in a beginner-friendly manner!

Develop a Next.js application that highlights the key features of Next.js along with a comprehensive CRUD AI Prompt sharing system utilizing a MongoDB database and implementing NextAuth authentication.

If you're getting started and need assistance or face any bugs, join our active Discord community with over 27k+ members. It's a place where people help each other out.

  • Next.js
  • MongoDB
  • NextAuth
  • TailwindCSS

πŸ‘‰ Modern Design with Glassmorphism Trend Style: A modern and visually appealing design, incorporating the glassmorphism trend style for a sleek and contemporary appearance.

πŸ‘‰ Discover and Share AI Prompts: Allow users to discover AI prompts shared by the community and create their own prompts to share with the world.

πŸ‘‰ Edit and Delete Created Prompts: Users have the ability to edit their created prompts at any time and delete them when needed.

πŸ‘‰ Profile Page: Each user gets a dedicated profile page showcasing all the prompts they've created, providing an overview of their contributions.

πŸ‘‰ View Other People's Profiles: Users can explore the profiles of other creators to view the prompts they've shared, fostering a sense of community.

πŸ‘‰ Copy to Clipboard: Implement a convenient "Copy to Clipboard" functionality for users to easily copy the AI prompts for their use.

πŸ‘‰ Search Prompts by Specific Tag: Allow users to search for prompts based on specific tags, making it easier to find prompts related to specific topics.

πŸ‘‰ Google Authentication using NextAuth: Enable secure Google authentication using NextAuth, ensuring a streamlined and trustworthy login experience.

πŸ‘‰ Responsive Website: Develop a fully responsive website to ensure optimal user experience across various devices, from desktops to smartphones

and many more, including code architecture and reusability

Follow these steps to set up the project locally on your machine.

Prerequisites

Make sure you have the following installed on your machine:

Cloning the Repository

git clone https://github.com/adrianhajdin/project_next_13_ai_prompt_sharing.git
cd project_next_13_ai_prompt_sharing

Installation

Install the project dependencies using npm:

npm install

Set Up Environment Variables

Create a new file named .env in the root of your project and add the following content:

NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_URL_INTERNAL=http://localhost:3000
NEXTAUTH_SECRET=
GOOGLE_ID=
GOOGLE_CLIENT_SECRET=
MONGODB_URI=

Replace the placeholder values with your actual credentials. You can obtain these credentials by signing up on these corresponding websites from Google Cloud Console, Cryptpool (for random Auth Secret), and MongoDB.

Running the Project

npm run dev

Open http://localhost:3000 in your browser to view the project.

globals.css
@import url("https://fonts.googleapis.com/css2?family=Inter:wght@100;200;300;400;500;600;700;800;900&display=swap");

@tailwind base;
@tailwind components;
@tailwind utilities;

/* 
  Note: The styles for this gradient grid background is heavily inspired by the creator of this amazing site (https://dub.sh) – all credits go to them! 
*/

.main {
  width: 100vw;
  min-height: 100vh;
  position: fixed;
  display: flex;
  justify-content: center;
  padding: 120px 24px 160px 24px;
  pointer-events: none;
}

.main:before {
  background: radial-gradient(circle, rgba(2, 0, 36, 0) 0, #fafafa 100%);
  position: absolute;
  content: "";
  z-index: 2;
  width: 100%;
  height: 100%;
  top: 0;
}

.main:after {
  content: "";
  background-image: url("/assets/images/grid.svg");
  z-index: 1;
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  opacity: 0.4;
  filter: invert(1);
}

.gradient {
  height: fit-content;
  z-index: 3;
  width: 100%;
  max-width: 640px;
  background-image: radial-gradient(
      at 27% 37%,
      hsla(215, 98%, 61%, 1) 0px,
      transparent 0%
    ),
    radial-gradient(at 97% 21%, hsla(125, 98%, 72%, 1) 0px, transparent 50%),
    radial-gradient(at 52% 99%, hsla(354, 98%, 61%, 1) 0px, transparent 50%),
    radial-gradient(at 10% 29%, hsla(256, 96%, 67%, 1) 0px, transparent 50%),
    radial-gradient(at 97% 96%, hsla(38, 60%, 74%, 1) 0px, transparent 50%),
    radial-gradient(at 33% 50%, hsla(222, 67%, 73%, 1) 0px, transparent 50%),
    radial-gradient(at 79% 53%, hsla(343, 68%, 79%, 1) 0px, transparent 50%);
  position: absolute;
  content: "";
  width: 100%;
  height: 100%;
  filter: blur(100px) saturate(150%);
  top: 80px;
  opacity: 0.15;
}

@media screen and (max-width: 640px) {
  .main {
    padding: 0;
  }
}

/* Tailwind Styles */

.app {
  @apply relative z-10 flex justify-center items-center flex-col max-w-7xl mx-auto sm:px-16 px-6;
}

.black_btn {
  @apply rounded-full border border-black bg-black py-1.5 px-5 text-white transition-all hover:bg-white hover:text-black text-center text-sm font-inter flex items-center justify-center;
}

.outline_btn {
  @apply rounded-full border border-black bg-transparent py-1.5 px-5 text-black transition-all hover:bg-black hover:text-white text-center text-sm font-inter flex items-center justify-center;
}

.head_text {
  @apply mt-5 text-5xl font-extrabold leading-[1.15] text-black sm:text-6xl;
}

.orange_gradient {
  @apply bg-gradient-to-r from-amber-500 via-orange-600 to-yellow-500 bg-clip-text text-transparent;
}

.green_gradient {
  @apply bg-gradient-to-r from-green-400 to-green-500 bg-clip-text text-transparent;
}

.blue_gradient {
  @apply bg-gradient-to-r from-blue-600 to-cyan-600 bg-clip-text text-transparent;
}

.desc {
  @apply mt-5 text-lg text-gray-600 sm:text-xl max-w-2xl;
}

.search_input {
  @apply block w-full rounded-md border border-gray-200 bg-white py-2.5 font-satoshi pl-5 pr-12 text-sm shadow-lg font-medium focus:border-black focus:outline-none focus:ring-0;
}

.copy_btn {
  @apply w-7 h-7 rounded-full bg-white/10 shadow-[inset_10px_-50px_94px_0_rgb(199,199,199,0.2)] backdrop-blur flex justify-center items-center cursor-pointer;
}

.glassmorphism {
  @apply rounded-xl border border-gray-200 bg-white/20 shadow-[inset_10px_-50px_94px_0_rgb(199,199,199,0.2)] backdrop-blur p-5;
}

.prompt_layout {
  @apply space-y-6 py-8 sm:columns-2 sm:gap-6 xl:columns-3;
}

/* Feed Component */
.feed {
  @apply mt-16 mx-auto w-full max-w-xl flex justify-center items-center flex-col gap-2;
}

/* Form Component */
.form_textarea {
  @apply w-full flex rounded-lg h-[200px] mt-2 p-3 text-sm text-gray-500 outline-0;
}

.form_input {
  @apply w-full flex rounded-lg mt-2 p-3 text-sm text-gray-500 outline-0;
}

/* Nav Component */
.logo_text {
  @apply max-sm:hidden font-satoshi font-semibold text-lg text-black tracking-wide;
}

.dropdown {
  @apply absolute right-0 top-full mt-3 w-full p-5 rounded-lg bg-white min-w-[210px] flex flex-col gap-2 justify-end items-end;
}

.dropdown_link {
  @apply text-sm font-inter text-gray-700 hover:text-gray-500 font-medium;
}

/* PromptCard Component */
.prompt_card {
  @apply flex-1 break-inside-avoid rounded-lg border border-gray-300 bg-white/20 bg-clip-padding p-6 pb-4 backdrop-blur-lg backdrop-filter md:w-[360px] w-full h-fit;
}

.flex-center {
  @apply flex justify-center items-center;
}

.flex-start {
  @apply flex justify-start items-start;
}

.flex-end {
  @apply flex justify-end items-center;
}

.flex-between {
  @apply flex justify-between items-center;
}
jsconfig.json
{
  "compilerOptions": {
    "paths": {
      "@*": ["./*"]
    }
  }
}
route.js
import Prompt from "@models/prompt";
import { connectToDB } from "@utils/database";

export const GET = async (request, { params }) => {
    try {
        await connectToDB()

        const prompt = await Prompt.findById(params.id).populate("creator")
        if (!prompt) return new Response("Prompt Not Found", { status: 404 });

        return new Response(JSON.stringify(prompt), { status: 200 })

    } catch (error) {
        return new Response("Internal Server Error", { status: 500 });
    }
}

export const PATCH = async (request, { params }) => {
    const { prompt, tag } = await request.json();

    try {
        await connectToDB();

        // Find the existing prompt by ID
        const existingPrompt = await Prompt.findById(params.id);

        if (!existingPrompt) {
            return new Response("Prompt not found", { status: 404 });
        }

        // Update the prompt with new data
        existingPrompt.prompt = prompt;
        existingPrompt.tag = tag;

        await existingPrompt.save();

        return new Response("Successfully updated the Prompts", { status: 200 });
    } catch (error) {
        return new Response("Error Updating Prompt", { status: 500 });
    }
};

export const DELETE = async (request, { params }) => {
    try {
        await connectToDB();

        // Find the prompt by ID and remove it
        await Prompt.findByIdAndRemove(params.id);

        return new Response("Prompt deleted successfully", { status: 200 });
    } catch (error) {
        return new Response("Error deleting prompt", { status: 500 });
    }
};
tailwind.config.js
/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    './pages/**/*.{js,ts,jsx,tsx,mdx}',
    './components/**/*.{js,ts,jsx,tsx,mdx}',
    './app/**/*.{js,ts,jsx,tsx,mdx}',
  ],
  theme: {
    extend: {
      fontFamily: {
        satoshi: ['Satoshi', 'sans-serif'],
        inter: ['Inter', 'sans-serif'],
      },
      colors: {
        'primary-orange': '#FF5722',
      }
    },
  },
  plugins: [],
}
user.js
username: {
    type: String,
    required: [true, 'Username is required!'],
    match: [/^(?=.{8,20}$)(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$/, "Username invalid, it should contain 8-20 alphanumeric letters and be unique!"]
  },

Assets used in the project can be found here

Advance your skills with Next.js 14 Pro Course

Enjoyed creating this project? Dive deeper into our PRO courses for a richer learning adventure. They're packed with detailed explanations, cool features, and exercises to boost your skills. Give it a go!

Project Banner

Accelerate your professional journey with the Expert Training program

And if you're hungry for more than just a course and want to understand how we learn and tackle tech challenges, hop into our personalized masterclass. We cover best practices, different web skills, and offer mentorship to boost your confidence. Let's learn and grow together!

Project Banner

project_next_14_ai_prompt_sharing's People

Contributors

adrianhajdin avatar sujatagunale 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

project_next_14_ai_prompt_sharing's Issues

Acsses denied

Application error: a client-side exception has occurred (see the browser console for more information).

/api/prompt/new 500 Internal Server Error)

POST http://localhost:3000/api/prompt/new 500 (Internal Server Error) page.jsx:22

`try {
const response = await fetch("/api/prompt/new", {
method: "POST",
body: JSON.stringify({
prompt: post.prompt,
userId: session?.user.id,
tag: post.tag,
}),
});

  if (response.ok) {
    router.push("/");
  }
} catch (error) {
  console.log(error);
} finally {
  setIsSubmitting(false);
}

};`

I dont have idea Why

Access Denied Error

Tried every possible ways but still didn't get through.

  1. Make sure the password match in .env and MONGO DB. I noticed sometimes the password does not update if you changed it.
  2. Make sure the < > are removed in the env file for the MONGODB_URI
  3. Make sure you add your email as an authorize tester in the Google Cloud project
  4. Make sure there are no trailing spaces in the IDs
  5. Also, make sure the user role is set to read and write. You can find this when you select the Atlas project, Security > Database Access > Edit > Built-in Role, and select it from the dropdown

Screenshot 2023-06-11 at 6 25 58 AM

Issue with "handleEdit" & "handleDelete"

I'm currently at implementing the logic for the handleEdit function in the page.jsx of the MyProfile, but there is a bug occuring.

It is not being directed to update-prompt route after using the router.push() method, also I checked for all the silly mistakes but could not find any. Then I discovered that in the PromptCard component, where the Edit and Delete buttons are being rendered after the

{session?.user.id === post.creator._id && pathName === '/profile' && (

Edit

Delete

)}

I got to that the even without clicking the buttons I was still getting the console logs. And I think this is the issue but cannot seem to find a solution any help

MongooseError

MongooseError: The uri parameter to openUri() must be a string, got "undefined". Make sure the first parameter to mongoose.connect() or mongoose.createConnection() is a string. Despite the .env file being in the root folder i still keep getting this error. Kindly assist, tried so many ways of debugging
Screenshot 2023-06-12 223302
Screenshot 2023-06-12 223203

Try signing in with a different account.

Hi guys,

When I tried to login with google giving me Try signing in with a different account. When turn back giving like this url http://localhost:3000/api/auth/signin?error=OAuthCallback
what do I need to do pass this error?

[next-auth][error][OAUTH_CALLBACK_ERROR]
https://next-auth.js.org/errors#oauth_callback_error JWT expired, now 1684530792, exp 1684530786 {
error: RPError: JWT expired, now 1684530792, exp 1684530786
at Client.validateJWT (webpack-internal:///(sc_server)/./node_modules/openid-client/lib/client.js:850:23)
at Client.validateIdToken (webpack-internal:///(sc_server)/./node_modules/openid-client/lib/client.js:637:67)
at Client.callback (webpack-internal:///(sc_server)/./node_modules/openid-client/lib/client.js:417:24)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async oAuthCallback (webpack-internal:///(sc_server)/./node_modules/next-auth/core/lib/oauth/callback.js:118:22)
at async Object.callback (webpack-internal:///(sc_server)/./node_modules/next-auth/core/routes/callback.js:18:83)
at async AuthHandler (webpack-internal:///(sc_server)/./node_modules/next-auth/core/index.js:202:38)
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:244:37) {
name: 'OAuthCallbackError',
code: undefined
},
providerId: 'google',
message: 'JWT expired, now 1684530792, exp 1684530786'

ACCESS DENIED ISSUE SOLVED in route.js, You can now sign in with Google and see result in MongoDB

Replace what you have in your route.js file in app/api/auth/[...nextauth] with the code below:

import NextAuth from 'next-auth';
import GoogleProvider from 'next-auth/providers/google';

import User from 'models/user';
import { connectToDB } from 'utils/database';

const handler = NextAuth({
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    })
  ],
  callbacks: {
    async session({ session }) {

      const sessionUser = await User.findOne({ email: session.user.email });
      session.user.id = sessionUser._id.toString();

      return session
    },
    async signIn({ user, account, profile, email, credentials }) {
      try {
        await connectToDB();
        const userExists = await User.findOne({ email: profile?.email });
        // if not, create a new document and save user in MongoDB
        if (userExists === null) {
          await User.create({
            email: profile?.email,
            username: profile?.name.replace(/\s+/g, '').toLowerCase(),
            image: user.image
          })
        }

        return true
      } catch (error) {
        console.log(error);
        return false
      }
      
    } 
  }
})

export { handler as GET, handler as POST }

The problem was the number of params in signIn callback. Please write in the order above and also use conditional ? as used in the try block of signIn asyn function above.

Let me know if this works for you too!

Cheers

Auth problems

const { data: session } = useSession()
const [ providers, setProviders ] = useState(null)

useEffect(() => {
    (async () => {
      const res = await getProviders();
      setProviders(res);
    })();
}, []);

I wrote provider like this, but alert(provider) still shows null, Can anyone help me with this problem?

Access Denied

Can someone please explain why this keeps happening once I try to sign in?
image

image

Access denied.

MongoServerError: bad auth : authentication failed
at Connection.onMessage (C:\Users\ashvi\Desktop\Wizard\node_modules\mongoose\node_modules\mongodb\lib\cmap\connection.js:202:26)
at MessageStream. (C:\Users\ashvi\Desktop\Wizard\node_modules\mongoose\node_modules\mongodb\lib\cmap\connection.js:61:60)
at MessageStream.emit (node:events:526:28)
at processIncomingData (C:\Users\ashvi\Desktop\Wizard\node_modules\mongoose\node_modules\mongodb\lib\cmap\message_stream.js:124:16)
at MessageStream._write (C:\Users\ashvi\Desktop\Wizard\node_modules\mongoose\node_modules\mongodb\lib\cmap\message_stream.js:33:9)
at writeOrBuffer (node:internal/streams/writable:389:12)
at _write (node:internal/streams/writable:330:10)
at MessageStream.Writable.write (node:internal/streams/writable:334:10)
at TLSSocket.ondata (node:internal/streams/readable:754:22)
at TLSWrap.onStreamRead (node:internal/stream_base_commons:190:23)
at TLSWrap.callbackTrampoline (node:internal/async_hooks:130:17) {
ok: 0,
code: 8000,
codeName: 'AtlasError',
connectionGeneration: 0,
[Symbol(errorLabels)]: Set(2) { 'HandshakeError', 'ResetPool' }
}
Error checking if user exists: Operation users.findOne() buffering timed out after 10000ms
image

Someone help please with this error!

Fetch through target failed: Unsupported URL scheme; Fallback: Помилка HTTP: ΠΊΠΎΠ΄ статусу 404, net::ERR_UNKNOWN_URL_SCHEME

TypeError: Failed to construct 'URL': Invalid

Application error: a client-side exception has occurred (see the browser console for more information).

SCR-20230620-lqun Everything was working fine, but after adding more than 10 prompts, I got a blink page with this error: Application error: a client-side exception has occurred (see the browser console for more information). in the browser console : typeError: Cannot read properties of undefined (reading 'image') at o (page-241b7b2b063c19b3.js:1:1965) at rd (2443530c-4218d3c23870e38f.js:9:38892) at iw (2443530c-4218d3c23870e38f.js:9:111601) at oI (2443530c-4218d3c23870e38f.js:9:89903) at 2443530c-4218d3c23870e38f.js:9:89752 at oA (2443530c-4218d3c23870e38f.js:9:89759) at ox (2443530c-4218d3c23870e38f.js:9:87479) at oE (2443530c-4218d3c23870e38f.js:9:86343) at j (139-3e2f9fb5e42f5af6.js:25:1398) at MessagePort.C (139-3e2f9fb5e42f5af6.js:25:1951)

next-auth error

I am about 1hr 35mins in the video and I am running into the following problem:

When pressing Sign-In on the Promptopia webpage, it says that I timed out, and displays the google sign-in button.
Upon pressing the sign-in button, the same problem occurs.

The error appears in the console upon attempting sign-in:

[next-auth][error][SIGNIN_OAUTH_ERROR] https://next-auth.js.org/errors#signin_oauth_error outgoing request timed out after 3500ms { error: { message: 'outgoing request timed out after 3500ms', stack: 'RPError: outgoing request timed out after 3500ms\n' + ' at eval (webpack-internal:///(sc_server)/./node_modules/openid-client/lib/helpers/request.js:115:19)\n' + ' at async Issuer.discover (webpack-internal:///(sc_server)/./node_modules/openid-client/lib/issuer.js:135:30)\n' + ' at async openidClient (webpack-internal:///(sc_server)/./node_modules/next-auth/core/lib/oauth/client.js:12:18)\n' + ' at async getAuthorizationUrl (webpack-internal:///(sc_server)/./node_modules/next-auth/core/lib/oauth/authorization-url.js:88:20)\n' + ' at async Object.signin (webpack-internal:///(sc_server)/./node_modules/next-auth/core/routes/signin.js:21:30)\n' + ' at async AuthHandler (webpack-internal:///(sc_server)/./node_modules/next-auth/core/index.js:259:36)\n' + ' at async NextAuthRouteHandler (webpack-internal:///(sc_server)/./node_modules/next-auth/next/index.js:49:30)\n' + ' at async NextAuth._args$ (webpack-internal:///(sc_server)/./node_modules/next-auth/next/index.js:83:24)\n' + ' at async eval (webpack-internal:///(sc_server)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:244:37)', name: 'RPError' }, providerId: 'google', message: 'outgoing request timed out after 3500ms' }

Things I have tried -

and then I ran:
curl -d "code=AUTHORIZATION_CODE&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&redirect_uri=YOUR_REDIRECT_URI&grant_type=authorization_code" -H "Content-Type: application/x-www-form-urlencoded" -X POST "https://oauth2.googleapis.com/token"

and I successfully yielded a JSON response, so it seems the issue is to do with my code, and not my google cloud project settings.

ALSO: I am running the next-js application in an Ubuntu virtual machine using Virtual Box.
The settings for the VBox is so that the wifi adapter is bridged.

The project is on my github as a repository under the name "share-prompts" for those who would like to see the code.

If anyone can help out with figuring out why this timeout is occurring, help is appreciated.

Module not found

image

I'm having this issue of Module not found while trying to do
import { signIn, signOut, useSession, getProviders} from 'next-auth/react' in Nav.jsx

Atlas Error Sign in Error Access Denied MongoDb [SOLVED]

So I've noticed there have been a lot of issues regarding the Mongoose Database not storing the share_prompt (users) collection. In the route.js file, changing callbacks to callback does NOT work, as the NextJS will just skip over this section and not allow MongoDB to save the collection. Here's my solution that worked for me:

STEP 1 - Add admin privileges to your user in the MongoDB ATLAS

  • Go to Database Access section of the MongoDB ATLAS, click on EDIT on the user that is in your MONGODB_URI in your .env file
  • Under the Built-in Role select the Atlas admin option and Update User to confirm changes.

1

2

STEP 2 - Change route.js signIn arguements

  • Go to route.js and find async signIn( { profile } ){ ... }
  • Change it to async signIn({ account, profile, user, credentials }) { ... } as shown in the picture. You can also find the copy the entire route.js file from my Repo

3

Additional Notes

If this doesn't work make sure that your MONGODB_URI variable in your .env file is properly populated with the correct username AND password.

Credit to Effam for finding the Step 2 of this solution here: #47

Errors thrown by next.js which work in youtube course

I am learning Next.js and I am currently at the beginning of prompt creation.

I code along the video and I ran in few issues (I don't know if anyone else did since I don't see those issues mentioned here or in youtube comments).

  1. Fetching image from Google threw me an error that hostname is not configured: I fixed it with remotePatterns which I found in Next.js docs. However, now I see in source code that you also set this in next.config.js (using domain, not patterns), but it was never mentioned in video (or maybe I skipped it).
  2. Getting user from database inside session callback throws me mongodb timeout error (buffering timed out after 10000ms), so I was required to add this line of code await connectToDB(); at the start of callbacks async session function (nextauth route.js). This happens when I login with google account, then stop the app and then start it again with npm run dev. Session still outputs my google account data, but User.findOne() fails since it can't connect to database. Is this line required if this was app for production?

Watchpack Error (watcher): Error: EACCES: permission denied, watch

Somebody encountered this error when running 'npm run dev': 'Watchpack Error (watcher): Error: EACCES: permission denied, watch.' It appears that the process is attempting to access folders outside of the project directory and does not have permission to access other folders in the Documents directory. I tried resolving this error by modifying the config files, but none of them provided a solution. I suspect it might be a bug in the Next.js version, as the application works and the server is enabled, but it still throws this error in the server logs. Do you have any ideas on how to solve this?

nextjs version [email protected] & also I tried with [email protected]

I solved error about Access Denied

I follow the #52
It works.

no change other files.

route.js

import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";

import User from "@models/user";
import { connectToDB } from "@utils/database";

const handler = NextAuth({
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
  ],
  callback: {
    async session({ session }) {
      // store the user id from MongoDB to session
      const sessionUser = await User.findOne({ email: session.user.email });
      session.user.id = sessionUser._id.toString();

      return session;
    },
    async signIn({ account, profile, user, credentials }) {
      try {
        await connectToDB();

        // check if user already exists
        const userExists = await User.findOne({ email: profile.email });

        // if not, create a new document and save user in MongoDB
        if (!userExists) {
          await User.create({
            email: profile.email,
            username: profile.name.replace(" ", "").toLowerCase(),
            image: profile.picture,
          });
        }

        return true;
      } catch (error) {
        console.log("Error checking if user exists: ", error.message);
        return false;
      }
    },
  },
});

export { handler as GET, handler as POST };

Access denied error, can't login

The app was working fine, but after adding the async codes into the callbacks. it stop login in and start showing access denied. the database is connect. i don't know what could be the issues.
db connect error
signin error

Access blocked: This app’s request is invalid

I cannot pass the authentication sign in page. It shows localhost 300 instead of 3000. When I click on error details I have attached the snapshot. If I add 300 then it works but not with 3000. How do I resolve this ?

Screenshot from 2023-05-13 21-23-43
Screenshot from 2023-05-13 21-16-33

Application error

Application error: a client-side exception has occurred (see the browser console for more information).
[Only On HomePage]

'post.creator.image' / 'post.creator.email' is undefined

image
Error seems to appear from this block of code for the image attribute.

         <Image
            src={post.creator.image}
            alt="user_image"
            width={40}
            height={40}
            className="rounded-full object-contain"
          />

This is probably a client-side error, as the back-end throws no error.
image

Any fixes? Or this is an issue bug?

Error: EPERM operation not permitted

After changing the next.config.js to the one JavaScript Mastery one, running npm run dev gives me this error:

 Error: EPERM: operation not permitted, open 'C:\Users\R\OneDrive\Desktop\share_prompts\my-app\.next\trace'
Emitted 'error' event on WriteStream instance at:
    at emitErrorNT (node:internal/streams/destroy:157:8)
    at emitErrorCloseNT (node:internal/streams/destroy:122:3)        
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  errno: -4048,
  code: 'EPERM',
  syscall: 'open',
  path: 'C:\\Users\\R\\OneDrive\\Desktop\\share_prompts\\my-app\\.next\\trace'

How are certain routes protected?

I was wondering how are certain routes like /profile and /create-prompt are not visible unless the user is authenticated? I don't see a check to make sure a user is authenticated before rendering a page and was just curious.

Inconsistent naming convention in globals.css

At 1:00:41 seconds into the video you write a "Tailwind class" called flex-between. This makes it seem like it is a native Tailwind class.

At the beginning of the video you said that your custom CSS will use '_' underscores. As someone learning Tailwind this was really confusingπŸ˜…. My intelligence tooltip was not appearing, I search and thought perhaps this is a deprecated class. I only then decided to check the globals.css file, just in case.

You could change the code now, but the video still has the '-' dash syntax. Perhaps a solution can be a pinned comment on your YouTube video with common errors.

Issue with feed

Does anyone have an issue where the feed is not pulling all the prompts from the db after deploying it to Vercel? If I click on a profile there are all the prompts from that user but on the feed page, it's missing some that were created by that user. It only happens on the Vercel deployed site, on my local environment there's no issue with the feed

Mongoose missing modules/ not compiling

Currently Im having an issue when accessing /create-post, I get that the User model cannot be read and is undefined.
After checking errors it seems I was missing some modules, I tried installing them one by one but then I reached snappy and its giving me a compiler error,

Please help with the configuration of the webpacks
here is the error: ./node_modules/mongoose/node_modules/mongodb/node_modules/@mongodb-js/zstd-win32-x64-msvc/zstd.win32-x64-msvc.node
Module parse failed: Unexpected character 'οΏ½' (1:2)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file

Sign in Error

I can't sign in, I checked everything like URLs and passwords already, what do you think about this error, maybe it's because I am in Iran and Google banned us but I use VPN and I don't think it's about it. this is the error 'Try signing in with a different account.'

[CLIENT_FETCH_ERROR] after deploying to the web using firebase

Do you know if anyone else has encountered the same issue? The application functions properly on localhost, but after deploying it to the web using Firebase, it fails to work. I have thoroughly reviewed the .env file and everything appears to be correct, yet the application still does not function.

The NEXTAUTH_URL:
image
image

The following error message is displayed:
image

Some common problems

  1. To make tailwind work (issues on video) you need to fix imports in files
    "app\profile\page.jsx" and "app\profile[id]\page.jsx"
    from
    import Profile from '@components/profile'
    to
    import Profile from '@components/Profile'
    try it myself - its fix a problem with real-time work with tailwind

  2. If we combining name and surname to one string its too big for Profile component, my solution was
    {name !== 'My' && window.innerWidth<400 ? ( <span className='blue_gradient'>{name.substring(0, 10)}... Profile</span> ): ( <span className='blue_gradient'>{name} Profile</span> )}

globals.css error

./styles/globals.css:75:5
Syntax error: C:\WORK\REACT\NEXTJS\promptopia\styles\globals.css The sm: class does not exist. If sm: is a custom class, make sure it is defined within a @layer directive.

73 |
74 | .app {

75 | @apply relative z-10 flex justify-center items-center flex-col max-w-7xl mx-auto sm: px-16 px-6;
| ^
76 | }
77 |

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.