Skip to content

Instantly share code, notes, and snippets.

@adrianhajdin
Created May 5, 2023 13:13
Show Gist options
  • Save adrianhajdin/6df61c6cd5ed052dce814a765bff9032 to your computer and use it in GitHub Desktop.
Save adrianhajdin/6df61c6cd5ed052dce814a765bff9032 to your computer and use it in GitHub Desktop.
Next.js 13 Full Course 2023 | Build and Deploy a Full Stack App Using the Official React Framework
@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;
}
{
"compilerOptions": {
"paths": {
"@*": ["./*"]
}
}
}
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 });
}
};
/** @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: [],
}
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!"]
},
@vladdg-dev
Copy link

@vladdg-dev Can you please share your repository link?

@maryam-nasir yes here it is https://github.com/vladdg-dev/ai-prompts

@hasanBafuleh
Copy link

I deployed the whole project. But when I add a prompt, the post gets updated in the database but doesn't reflect on the main page of the website. Although the new post is visible in the user profile, the main page isn't updating. Have anyone encountered this issue before, and if so, do you have any insights on how to address it?

@Ilham-r
Copy link

Ilham-r commented Feb 24, 2024

Screenshot 2024-02-25 001559 how to solve this error

i gave an answer above u can try it

@hasanBafuleh
Copy link

When I run npm run dev and check my website on the local server, everything looks good. The data shows up fine, and if I tweak things in MongoDB, my local site updates accordingly. But here's the problem – when I deploy it to Vercel, even though I set up everything right, the data doesn't update. I did all the ENV variable stuff, deployment went well, and the data is there, but if I make changes in MongoDB afterward, my site on Vercel doesn't reflect those changes. It just sticks with the initial data, and it only appears if I redeploy the project.

@spexzee
Copy link

spexzee commented Feb 25, 2024

Screenshot (225) can someone assist me with this error please

    if (!userExists) {
              await User.create({
                email: profile.email,
                username: profile.name.replace(" ", "").toLowerCase(),
                image: profile.image,
              })

in username, write like this username: profile.login , without replace method.

and in user model, remove match key,
write like this

    username: { 
        type: String, 
        require: [true, "Username is required!"], 
    }, 

optional : wrap GOOGLE_CLIENT_SECRET in single (' ') or double (" ") quote,

@Danbob81
Copy link

@Danbob81 I am facing the same usesession issue, but I don;t know how to resolve it, please help

@Developer-Kings-dev Sorry, I've had a busy couple of weeks and just saw this. Have you been able to resolve it?

@Developer-Kings-dev
Copy link

@Danbob81 I am facing the same usesession issue, but I don;t know how to resolve it, please help

@Developer-Kings-dev Sorry, I've had a busy couple of weeks and just saw this. Have you been able to resolve it?

@Danbob81 no I have not been able to resolve it; below is the code of the nav.tsx
`"use client";

import Link from "next/link";
import Image from "next/image";
import { useState, useEffect } from "react";
import { signIn, signOut, useSession, getProviders } from 'next-auth/react';
import { set } from "mongoose";
import { SessionProvider } from "next-auth/react"

const Nav = () => {
const { data: session } = useSession();

const [Providers, setProviders] = useState(null);
const [toggleDropdown, setToggleDropdown] = useState(false);

useEffect(() => {
const setUpProviders = async () => {
const response = await getProviders();

  setProviders(response);
}

setProviders();

}, [])

return (

<nav className="flex-between w-full mb-16 pt-3">
  <Link legacyBehavior href="/" passHref>
    <a className="flex gap-2 flex-center">
      <Image 
        src="/assets/images/logo.svg"
        alt="Promptopia Logo"
        width={30}
        height={30}
        className="object-contain"
      />
      <p className="logo-text">Promptopia</p>
    </a>
  </Link>


  {/* Desktop Navigation */}
  <div className="sm:flex hidden">
    {session?.user ? (
      <div className="flex gap-3 md:gap-5">
        <Link href="/create-prompt" className="black_btn">
          Create Post
        </Link>

        <button type="button" onClick={signOut} className="outline_btn">
          Sign Out
        </button>

        <Link legacyBehavior href="/profile" passHref>
            <image
              src= {session.user.image}
              width={37}
              height={37}
              className="rounded-full"
              alt="Profile"
            />
        </Link>
      </div>
    ): (
      <>
         {Providers &&
          Object.values(Providers).map((provider) => (
            <button
              type="button"
              key={provider.name}
              onClick={() => signIn(provider.id)} className="black_btn"          
            >
              Sign In
            </button>
          ))}
      </>     
    )}
  </div>

  {/* Mobile Navigation */}
  <div className="sm:hidden flex relative">
    {session?.user ? (
      <div className="flex">
         <img
              src= {session.user.image}
              width={37}
              height={37}
              className="rounded-full"
              alt="Profile"
              onClick={() => setToggleDropdown((prev) => !prev)}
            />

            {toggleDropdown && (
              <div className="dropdown">
                <Link
                  href="/profile"
                  className="dropdown-link"
                  onClick={() => setToggleDropdown(false)}
                >
                  My Profile
                </Link>
                <Link
                  href="/create-prompt"
                  className="dropdown-link"
                  onClick={() => setToggleDropdown(false)}
                >
                  Create Prompt
                </Link>
                <button
                   type="button"
                   onClick={() => {
                    setToggleDropdown(false);
                    signOut();
                   }} 
                   className="mt-5 w-full black_btn"    
                >
                  Sign Out
                </button>
              </div>
            )}
      </div>
    ) : (
      <>
      {Providers &&
       Object.values(Providers).map((provider) => (
         <button
           type="button"
           key={provider.name}
           onClick={() => signIn(provider.id)} className="black_btn"          
         >
           Sign In
         </button>
       ))}
   </>     
 )}
  </div>

</nav>

)
}

export default Nav;`
localhost_3000
Uploading Desktop screenshot (4).png…

@NarendranKT
Copy link

NarendranKT commented Feb 29, 2024

Hi did anyone got this error?? and if you have resolved it, please pass the solutions.

I have done everything. but again and again got this error..

Nav.jsx:15 [next-auth][error][CLIENT_FETCH_ERROR] https://next-auth.js.org/errors#client_fetch_error Unexpected token '<', "<!DOCTYPE "... is not valid JSON {error: {…}, url: '/api/auth/providers', message: Unexpected token '<', "<!DOCTYPE "... is not valid JSON} logger.js:92 POST http://localhost:3000/api/auth/_log 404 (Not Found) Nav.jsx:15 POST http://localhost:3000/api/auth/_log 404 (Not Found) logger.js:92 POST http://localhost:3000/api/auth/_log 404 (Not Found) Nav.jsx:15 POST http://localhost:3000/api/auth/_log 404 (Not Found)

app-index.js:35 [next-auth][error][CLIENT_FETCH_ERROR] https://next-auth.js.org/errors#client_fetch_error Unexpected token '<', "<!DOCTYPE "... is not valid JSON {error: {…}, url: '/api/auth/session', message: Unexpected token '<', "<!DOCTYPE "... is not valid JSON}

@LaheriTushar08
Copy link

Hi, I'm having trouble with this error:

Unhandled Runtime Error Error: [next-auth]: useSession must be wrapped in a <SessionProvider />

Screenshot 2024-01-29 141448

Has anyone else encountered this? How did you resolve it? I checked the NextAuth.js documentation and have added the following but it still gives me the same error:

Configure Shared session state To be able to use useSession first you'll need to expose the session context, <SessionProvider />, at the top level of your application:

pages/_app.jsx `import { SessionProvider } from "next-auth/react"

export default function App({ Component, pageProps: { session, ...pageProps }, }) { return ( <Component {...pageProps} /> ) }`

Am I missing something? Any help would be appreciated, thanks.

Hey there, even i encountered this error while watching the tutorial , after spending an hour of debugging I found out that I was only missing a " ; " 😢 at the line "export default Provider" in the file Providers.jsx , it worked out for me , just check if it works for you.

@Adriankn0rr
Copy link

Adriankn0rr commented Mar 1, 2024

After adding the Provider around the {children}, in the layout.js, I receive an error:

Bildschirmfoto 2024-03-01 um 12 34 53

Error: Objects are not valid as a React child (found: object with keys {children}). If you meant to render a collection of children, use an array instead.

The Provider.js looks as following:

"use client" ;

import { SessionProvider } from 'next-auth/react';

const Provider = (children, session) => {
  return (
   <SessionProvider session={session}>
    {children}
   </SessionProvider>
  )
}

export default Provider

the layout.js looks as following:

import "./globals.css";
import Nav from "./Nav.js"
import Provider from "@/components/Provider";


export const metadata = {
  title: "Create Next App",
  description: "Generated by create next app",
};

const RootLayout = ({children}) => {
  return (
    <html lang="en">

      <body >
      <Provider>
        <Nav></Nav>
          {children}
          </Provider>
         </body>
    </html>
  )
}
export default RootLayout;

@charith-codex
Copy link

charith-codex commented Mar 1, 2024

It's happen when you try to sign in with Gmail account. When Gmail account name characters not in 8-20 range. change the range in user.js username area.

#before
match: [/^(?=.{8,20}$)

#after
match: [/^(?=.{1,50}$)

image

@silent-kid
Copy link

Module not found: Can't resolve '@styles/globals.css'

1 | import '@styles/globals.css';
2 | import { Children } from 'react';
3 |
4 | export const metadata = {

https://nextjs.org/docs/messages/module-not-found ⨯ ./app/layout.jsx:1:0 Module not found: Can't resolve '@styles/globals.css'

1 | import '@styles/globals.css';
2 | import { Children } from 'react';
3 |
4 | export const metadata = {

https://nextjs.org/docs/messages/module-not-found

warn - No utility classes were detected in your source files. If this is unexpected, double-check the content option in your Tailwind CSS configuration. warn - https://tailwindcss.com/docs/content-configuration ⨯ ./styles/globals.css:75:5 Syntax error: C:\Users\kamal\OneDrive\Desktop\Project 101\Newer Projects\prompty\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 |
⚠ Fast Refresh had to perform a full reload due to a runtime error.
[webpack.cache.PackFileCacheStrategy] Skipped not serializable cache item 'Compilation/modules|C:\Users\kamal\OneDrive\Desktop\Project 101\Newer Projects\prompty\node_modules\next\dist\build\webpack\loaders\css-loader\src\index.js??ruleSet[1].rules[11].oneOf[12].use[2]!C:\Users\kamal\OneDrive\Desktop\Project 101\Newer Projects\prompty\node_modules\next\dist\build\webpack\loaders\postcss-loader\src\index.js??ruleSet[1].rules[11].oneOf[12].use[3]!C:\Users\kamal\OneDrive\Desktop\Project 101\Newer Projects\prompty\styles\globals.css': No serializer registered for PostCSSSyntaxError
while serializing webpack/lib/cache/PackFileCacheStrategy.PackContentItems -> webpack/lib/NormalModule -> webpack/lib/ModuleBuildError -> PostCSSSyntaxError

i get this error in every next project, i even tried using the exact next js version he used and still there is this error!!!!! in the previous project also when i copied the globals.css it gave me the same error, and i think its a very small error, can anyone help me with this?

{ "compilerOptions": { "paths": { "@*": ["./*"] } } }
make sure your jsconfig.json look like this

@Sailwayfun
Copy link

I'm using TypeScript and the compiler tells me "useNewUrlParser" does not exists on type ConnectionOptions.

Then, I look up StackOverflow, and find someone mention that the useNewUrlParser and useUnifiedTopology is no longer needed after mongoose 6.0

useNewUrlParser, useUnifiedTopology, useFindAndModify, and useCreateIndex are no longer supported options. Mongoose 6 always behaves as if useNewUrlParser, useUnifiedTopology, and useCreateIndex are true, and useFindAndModify is false. Please remove these options from your code.

Mongoose Document

@AnupriyaHaridas
Copy link

any body facing this same error in vercel deployment ? Screenshot 2024-02-09 at 1 23 38 PM
How did you resolve it?

I faced the same error while deploying on Vercel. I managed to get it fixed by wrapping the UpdatePrompt component in Suspense. Attaching the link to my project's update-prompt/page.jsx for reference below:

https://github.com/maryam-nasir/intelli-prompts/blob/master/app/update-prompt/page.jsx

It worked like a charm!! I really appreciate your assistance. Thank you so much!

@deni9309
Copy link

deni9309 commented Mar 4, 2024

Module not found: Can't resolve '@styles/globals.css'

1 | import '@styles/globals.css';
2 | import { Children } from 'react';
3 |
4 | export const metadata = {

https://nextjs.org/docs/messages/module-not-found ⨯ ./app/layout.jsx:1:0 Module not found: Can't resolve '@styles/globals.css'

1 | import '@styles/globals.css';
2 | import { Children } from 'react';
3 |
4 | export const metadata = {

https://nextjs.org/docs/messages/module-not-found
warn - No utility classes were detected in your source files. If this is unexpected, double-check the content option in your Tailwind CSS configuration. warn - https://tailwindcss.com/docs/content-configuration ⨯ ./styles/globals.css:75:5 Syntax error: C:\Users\kamal\OneDrive\Desktop\Project 101\Newer Projects\prompty\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 |
⚠ Fast Refresh had to perform a full reload due to a runtime error.
[webpack.cache.PackFileCacheStrategy] Skipped not serializable cache item 'Compilation/modules|C:\Users\kamal\OneDrive\Desktop\Project 101\Newer Projects\prompty\node_modules\next\dist\build\webpack\loaders\css-loader\src\index.js??ruleSet[1].rules[11].oneOf[12].use[2]!C:\Users\kamal\OneDrive\Desktop\Project 101\Newer Projects\prompty\node_modules\next\dist\build\webpack\loaders\postcss-loader\src\index.js??ruleSet[1].rules[11].oneOf[12].use[3]!C:\Users\kamal\OneDrive\Desktop\Project 101\Newer Projects\prompty\styles\globals.css': No serializer registered for PostCSSSyntaxError
while serializing webpack/lib/cache/PackFileCacheStrategy.PackContentItems -> webpack/lib/NormalModule -> webpack/lib/ModuleBuildError -> PostCSSSyntaxError

i get this error in every next project, i even tried using the exact next js version he used and still there is this error!!!!! in the previous project also when i copied the globals.css it gave me the same error, and i think its a very small error, can anyone help me with this?

{ "compilerOptions": { "paths": { "@*": ["./*"] } } } make sure your jsconfig.json look like this

@silent-kid
Hello! I had the same issue and I managed to solve it by wrapping all 'custom' CSS classes in globals.css @layer utilities { .... classes here }
You can look at the image:
https://drive.google.com/file/d/1uF7qobfbKvx8R7ZGc8sBUdD4U_puagY3/view?usp=sharing

I hope this will help you too :)

@manojt5
Copy link

manojt5 commented Mar 9, 2024

When I run npm run dev and check my website on the local server, everything looks good. The data shows up fine, and if I tweak things in MongoDB, my local site updates accordingly. But here's the problem – when I deploy it to Vercel, even though I set up everything right, the data doesn't update. I did all the ENV variable stuff, deployment went well, and the data is there, but if I make changes in MongoDB afterward, my site on Vercel doesn't reflect those changes. It just sticks with the initial data, and it only appears if I redeploy the project.

Hey @hasanBafuleh , having the same issue, have you got any clue on how to resolve this?

@hasanBafuleh
Copy link

When I run npm run dev and check my website on the local server, everything looks good. The data shows up fine, and if I tweak things in MongoDB, my local site updates accordingly. But here's the problem – when I deploy it to Vercel, even though I set up everything right, the data doesn't update. I did all the ENV variable stuff, deployment went well, and the data is there, but if I make changes in MongoDB afterward, my site on Vercel doesn't reflect those changes. It just sticks with the initial data, and it only appears if I redeploy the project.

Hey @hasanBafuleh , having the same issue, have you got any clue on how to resolve this?

Yes, The problem is with how Vercel deals with the '/api/prompt' route in ISR, and it doesn't update properly. To fix this, we want to move it out of ISR. To do that, just add 'revalidate=0' inside the '/api/prompt/route.js' file like this:

import Prompt from "@models/prompt";
import { connectToDB } from "@utils/database";

export const revalidate = 0;

export const GET = async (request) => {......}

@manojt5
Copy link

manojt5 commented Mar 14, 2024

When I run npm run dev and check my website on the local server, everything looks good. The data shows up fine, and if I tweak things in MongoDB, my local site updates accordingly. But here's the problem – when I deploy it to Vercel, even though I set up everything right, the data doesn't update. I did all the ENV variable stuff, deployment went well, and the data is there, but if I make changes in MongoDB afterward, my site on Vercel doesn't reflect those changes. It just sticks with the initial data, and it only appears if I redeploy the project.

Hey @hasanBafuleh , having the same issue, have you got any clue on how to resolve this?

Yes, The problem is with how Vercel deals with the '/api/prompt' route in ISR, and it doesn't update properly. To fix this, we want to move it out of ISR. To do that, just add 'revalidate=0' inside the '/api/prompt/route.js' file like this:

import Prompt from "@models/prompt"; import { connectToDB } from "@utils/database";

export const revalidate = 0;

export const GET = async (request) => {......}

Hey, it's working, thanks @hasanBafuleh!

@keithrincon
Copy link

I was having an issue off access being denied and stuff... tried everything until I configured this part by clicking the testing option.
Screenshot 2024-04-03 at 1 21 39 PM

@vverma2010
Copy link

Hi did anyone got this error?? and if you have resolved it, please pass the solutions.

I have done everything. but again and again got this error..

Nav.jsx:15 [next-auth][error][CLIENT_FETCH_ERROR] https://next-auth.js.org/errors#client_fetch_error Unexpected token '<', "<!DOCTYPE "... is not valid JSON {error: {…}, url: '/api/auth/providers', message: Unexpected token '<', "<!DOCTYPE "... is not valid JSON} logger.js:92 POST http://localhost:3000/api/auth/_log 404 (Not Found) Nav.jsx:15 POST http://localhost:3000/api/auth/_log 404 (Not Found) logger.js:92 POST http://localhost:3000/api/auth/_log 404 (Not Found) Nav.jsx:15 POST http://localhost:3000/api/auth/_log 404 (Not Found)

app-index.js:35 [next-auth][error][CLIENT_FETCH_ERROR] https://next-auth.js.org/errors#client_fetch_error Unexpected token '<', "<!DOCTYPE "... is not valid JSON {error: {…}, url: '/api/auth/session', message: Unexpected token '<', "<!DOCTYPE "... is not valid JSON}

@NarendranKT I also faced the same issue but then I resolved it. This issue occurs due to the wrong directory location of "api" folder.

Do let me know if you're using "src" folder structure or 'app' folder structure.

@vverma2010
Copy link

I'm using TypeScript and the compiler tells me "useNewUrlParser" does not exists on type ConnectionOptions.

Then, I look up StackOverflow, and find someone mention that the useNewUrlParser and useUnifiedTopology is no longer needed after mongoose 6.0

useNewUrlParser, useUnifiedTopology, useFindAndModify, and useCreateIndex are no longer supported options. Mongoose 6 always behaves as if useNewUrlParser, useUnifiedTopology, and useCreateIndex are true, and useFindAndModify is false. Please remove these options from your code.

Mongoose Document

Yes correct, these props are no longer required.

@mihirksingh21
Copy link

http://localhost:3000/api/auth/error?error=AccessDenied
image

error
⚠ Invalid next.config.mjs options detected:
⚠ Unrecognized key(s) in object: 'appDir' at "experimental"
⚠ See more info here: https://nextjs.org/docs/messages/invalid-next-config
✓ Ready in 2.4s

/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
appDir: true,
serverComponentsExternalPackages: ["mongoose"],
},
images: {
domains: ['lh3.googleusercontent.com'],
},
webpack(config) {
config.experiments = {
...config.experiments,
topLevelAwait: true,
};
return config;
}
};

export default nextConfig;

@JaredPL
Copy link

JaredPL commented Apr 14, 2024

http://localhost:3000/api/auth/error?error=AccessDenied image

error ⚠ Invalid next.config.mjs options detected: ⚠ Unrecognized key(s) in object: 'appDir' at "experimental" ⚠ See more info here: https://nextjs.org/docs/messages/invalid-next-config ✓ Ready in 2.4s

/** @type {import('next').NextConfig} */ const nextConfig = { experimental: { appDir: true, serverComponentsExternalPackages: ["mongoose"], }, images: { domains: ['lh3.googleusercontent.com'], }, webpack(config) { config.experiments = { ...config.experiments, topLevelAwait: true, }; return config; } };

export default nextConfig;

Try this:

/** @type {import('next').NextConfig} */
const nextConfig = {
images: {
remotePatterns: [
{
protocol: "https",
hostname: "lh3.googleusercontent.com",
pathname: "**",
},
],
},
webpack(config) {
config.experiments = {
...config.experiments,
topLevelAwait: true,
};
return config;
},
};

export default nextConfig;

https://stackoverflow.com/questions/77736233/unrecognized-keys-in-object-appdir-at-experimental-next-js-14-0-4-error

This will work if you use NEXT 14. I also fixed error for images. Make sure your file has .mjs extension and do what this guy in youtube comment section suggested.
yt-comment

@GiacomoVilla14
Copy link

GiacomoVilla14 commented Apr 18, 2024

http://localhost:3000/api/auth/error?error=AccessDenied image
error ⚠ Invalid next.config.mjs options detected: ⚠ Unrecognized key(s) in object: 'appDir' at "experimental" ⚠ See more info here: https://nextjs.org/docs/messages/invalid-next-config ✓ Ready in 2.4s
/** @type {import('next').NextConfig} */ const nextConfig = { experimental: { appDir: true, serverComponentsExternalPackages: ["mongoose"], }, images: { domains: ['lh3.googleusercontent.com'], }, webpack(config) { config.experiments = { ...config.experiments, topLevelAwait: true, }; return config; } };
export default nextConfig;

Try this:

/** @type {import('next').NextConfig} */ const nextConfig = { images: { remotePatterns: [ { protocol: "https", hostname: "lh3.googleusercontent.com", pathname: "**", }, ], }, webpack(config) { config.experiments = { ...config.experiments, topLevelAwait: true, }; return config; }, };

export default nextConfig;

https://stackoverflow.com/questions/77736233/unrecognized-keys-in-object-appdir-at-experimental-next-js-14-0-4-error

This will work if you use NEXT 14. I also fixed error for images. Make sure your file has .mjs extension and do what this guy in youtube comment section suggested. yt-comment

The steps shown in the image didn't work for me but instead I looked up online and found a regex to select every single space from the profile.name value.

username: profile.name.replace(/\s+/g, "").toLowerCase()

Credits to: https://www.geeksforgeeks.org/how-to-replace-multiple-spaces-with-single-space-in-javascript/#:~:text=Method%201%3A%20Using%20replace()%20Method

Using this fragment of code i was able to sign in to my account

@Shyam-crypto
Copy link

Guys i'm stuck with this error.anybody have a solution to this
⨯ Error: [next-auth]: useSession must be wrapped in a
at Nav (./components/Nav.jsx:19:90)
session

@pavansbhat
Copy link

pavansbhat commented Apr 27, 2024

Hi did anyone got this error?? and if you have resolved it, please pass the solutions.

I have done everything. but again and again got this error..

Nav.jsx:15 [next-auth][error][CLIENT_FETCH_ERROR] https://next-auth.js.org/errors#client_fetch_error Unexpected token '<', "<!DOCTYPE "... is not valid JSON {error: {…}, url: '/api/auth/providers', message: Unexpected token '<', "<!DOCTYPE "... is not valid JSON} logger.js:92 POST http://localhost:3000/api/auth/_log 404 (Not Found) Nav.jsx:15 POST http://localhost:3000/api/auth/_log 404 (Not Found) logger.js:92 POST http://localhost:3000/api/auth/_log 404 (Not Found) Nav.jsx:15 POST http://localhost:3000/api/auth/_log 404 (Not Found)

app-index.js:35 [next-auth][error][CLIENT_FETCH_ERROR] https://next-auth.js.org/errors#client_fetch_error Unexpected token '<', "<!DOCTYPE "... is not valid JSON {error: {…}, url: '/api/auth/session', message: Unexpected token '<', "<!DOCTYPE "... is not valid JSON}

You are probably rendering it wrong in layout.jsx file inside RootLayout.

Try this:

import React from "react";
import "@styles/globals.css";
import Nav from "@components/Nav";
import Provider from "@components/Provider";

export const metadata = {
  title: "Promptopia",
  description: "Discover & Share prompts",
};

const RootLayout = ({ children }) => {
  return (
    <html lang="en">
      <body>
        <Provider>
          <div className="main">
            <div className="gradient" />
          </div>
          <main className="app">
            <Nav />
            {children}
          </main>
        </Provider>
      </body>
    </html>
  );
};

export default RootLayout;

@pavansbhat
Copy link

http://localhost:3000/api/auth/error?error=AccessDenied image

error ⚠ Invalid next.config.mjs options detected: ⚠ Unrecognized key(s) in object: 'appDir' at "experimental" ⚠ See more info here: https://nextjs.org/docs/messages/invalid-next-config ✓ Ready in 2.4s

/** @type {import('next').NextConfig} */ const nextConfig = { experimental: { appDir: true, serverComponentsExternalPackages: ["mongoose"], }, images: { domains: ['lh3.googleusercontent.com'], }, webpack(config) { config.experiments = { ...config.experiments, topLevelAwait: true, }; return config; } };

export default nextConfig;

Keep the next.config.mjs as it is.
Create a new file with the name next.config.js in your root directory and add the following code in this file.

/** @type {import('next').NextConfig} */
const nextConfig = {
  experimental: {
    appDir: true,
    serverComponentsExternalPackages: ["mongoose"],
  },
  images: {
    domains: ["lh3.googleusercontent.com"],
  },
  webpack(config) {
    config.experiments = {
      ...config.experiments,
      topLevelAwait: true,
    };
    return config;
  },
};

module.exports = nextConfig;

@pavansbhat
Copy link

Guys i'm stuck with this error.anybody have a solution to this ⨯ Error: [next-auth]: useSession must be wrapped in a at Nav (./components/Nav.jsx:19:90) session

So if you watch the video, you need to add the following code inside Provider.jsx file inside your component folder.

"use client";
import React from "react";
import { SessionProvider } from "next-auth/react";

const Provider = ({ children, session }) => {
  return <SessionProvider session={session}>{children}</SessionProvider>;
};

export default Provider;

and after that inside layout.jsx file inside your create-prompt folder you need to wrap everything inside the body tag with the Provider component as follows.

import React from "react";
import "@styles/globals.css";
import Nav from "@components/Nav";
import Provider from "@components/Provider";

export const metadata = {
  title: "Promptopia",
  description: "Discover & Share prompts",
};

const RootLayout = ({ children }) => {
  return (
    <html lang="en">
      <body>
        <Provider>
          <div className="main">
            <div className="gradient" />
          </div>
          <main className="app">
            <Nav />
            {children}
          </main>
        </Provider>
      </body>
    </html>
  );
};

export default RootLayout;

Hope this solves your issue.

@Thai-Huynh0510
Copy link

anyone got 500 error while deleting? my edit works fine I have checked my code few times but everything seems fine
image

@kevinhangkh
Copy link

I am getting the Access denied error when trying to log in. This happens after putting the session() and signIn() functions in the callbacks.
image
Please help me figure this out.

you find the error? i have de same issue and i am very lost

  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

In case all of these don't work, try replacing your route.js with the one from the repo. I was missing some returns in the signIn function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment