Next.js Discord

Discord Forum

Next, Docker, Plesk and I have no idea what the error could be.

Unanswered
MeKa posted this in #help-forum
Open in Discord
Avatar
MeKaOP
The project runs on "localhost" without any problems. There is no error when I run "npm run build", but when I build "docker build ./ -t mekavip:1.0.7" with docker, this error appears.

The problem is that the project works very well, but when I build it with Docker and publish it to Plesk, some "URL" addresses give an "Internal Server Error" error. The URL addresses that give this error are the "/login", "/register" pages and the "/panel" url address linked to "next-auth", but when the "panel" url address does not have login permission, it automatically redirects to the "/login" url page.

  => => # Learn more: https://nextjs.org/docs/api-reference/edge-runtime
  => => # Import trace for requested module:
  => => # ./node_modules/bcryptjs/dist/bcrypt.js
  => => # ./lib/auth.config.ts
  => => # ./lib/auth.ts
  => => # Linting and checking validity of types ...

23 Replies

Avatar
MeKaOP
/lib/auth.ts

import NextAuth from "next-auth";
import { PrismaAdapter } from "@auth/prisma-adapter";
import prisma from "prismadb";
import authConfig from "auth.config";

export const { handlers, auth, signIn, signOut } = NextAuth({
  basePath: "/api/auth",
  secret: process.env.AUTH_SECRET,
  debug: process.env.NODE_ENV !== "production",
  adapter: PrismaAdapter(prisma),
  trustHost: true,
  ...authConfig,
});
/lib/auth.config.ts

import type { NextAuthConfig } from "next-auth";
import GoogleProvider from "next-auth/providers/google";
import CredentialsProvider from "next-auth/providers/credentials";
import { compare } from "bcryptjs";
import prisma from "prismadb";

export default {
  providers: [
    CredentialsProvider({
      id: "credentials",
      name: "Credentials",
      credentials: {
        email: { label: "Email", type: "text" },
        password: { label: "Password", type: "password" },
      },
      async authorize(credentials) {
        if (!credentials?.email || !credentials?.password) {
          throw new Error("Something went wrong.");
        }

        try {
          const user = await prisma.user.findUnique({
            where: {
              email: credentials.email as string,
            },
          });
          const isPasswordCorrect = await compare(
            credentials?.password as string,
            user?.password as string
          );
          if (user) {
            if (isPasswordCorrect) {
              return Promise.resolve(user);
            } else {
              throw new Error("Incorrect Credentials!");
            }
          } else {
            throw new Error("No such user found!");
          }
        } catch (err) {
          throw new Error(err as string);
        }
      },
    }),
  ],
  pages: {
    signIn: "/login",
  },
  session: {
    strategy: "jwt",
    maxAge: 24 * 60 * 60, // 1 day
    updateAge: 60 * 60, // 1 hour
  },
  callbacks: {
    session: async ({ session, token }) => {
      if (session?.user) {
        session.user.id = token.uid as string;
      }
      return session;
    },
    async jwt({ token, user }: any) {
      if (user) {
        let { password, ...userInfo } = user;
        token.role = userInfo.role;
        token.user = userInfo;
      }
      return token;
    },
  },
} satisfies NextAuthConfig;
middleware.ts

import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import createIntlMiddleware from "next-intl/middleware";
import { auth } from "auth";

const locales = ["en", "de", "ru", "fr"];
const authPages = ["/login", "/register"];
const publicPages = [
  "/",
  "/login",
  "/register",
  "/create-reservation",
  "/services",
  "/contact",
  "/about-us",
  "/mission-vision",
  "/our-privacy-policy",
  "/query",
];

const intlMiddleware = createIntlMiddleware({
  locales,
  defaultLocale: "en",
  localePrefix: "always",
});
const testPathnameRegex = (pages: string[], pathName: string): boolean => {
  return RegExp(
    `^(/(${locales.join("|")}))?(${pages
      .flatMap((p) => (p === "/" ? ["", "/"] : p))
      .join("|")})/?$`,
    "i"
  ).test(pathName);
};

const authMiddleware = auth((req) => {
  const isAuthPage = testPathnameRegex(authPages, req.nextUrl.pathname);
  const session = req.auth;

  // Redirect to sign-in page if not authenticated
  if (!session && !isAuthPage) {
    return NextResponse.redirect(new URL("/login", req.nextUrl));
  }

  // Redirect to home page if authenticated and trying to access auth pages
  if (session && isAuthPage) {
    return NextResponse.redirect(new URL("/", req.nextUrl));
  }

  return intlMiddleware(req);
});

const middleware = (req: NextRequest) => {
  const isPublicPage = testPathnameRegex(publicPages, req.nextUrl.pathname);
  const isAuthPage = testPathnameRegex(authPages, req.nextUrl.pathname);

  if (isAuthPage) {
    return (authMiddleware as any)(req);
  }

  if (isPublicPage) {
    return intlMiddleware(req);
  } else {
    return (authMiddleware as any)(req);
  }
};

export const config = {
  matcher: ["/((?!api|_next|.*\\..*).*)"],
};

export default middleware;
Avatar
MeKaOP
Plesk Console
Image
Avatar
MeKaOP
Is there anyone?
Avatar
averydelusionalperson
IG it's error related to docker, plesk, whatever it is. I doubt you'll get that much help here, it isn't really next.js related question here.
you've deployed it wrongly ig
can you try upgrading to latest next version?
Avatar
MeKaOP
The site is already working, there is no problem other than "Interval Server Error", I think it is related to "next-auth".
Since I cannot "/login", I cannot access the "/panel" (admin) page.
Avatar
averydelusionalperson
did you try setting NEXTAUTH_URL?
seems like something related to it to me
Avatar
MeKaOP
this is the version “next 14.1.1”
Avatar
averydelusionalperson
yeah, IK. saw the screenshot
Avatar
MeKaOP
This
Avatar
joulev
please do not bump then delete and bump again
Avatar
MeKaOP
Ok sir, thank you
Avatar
Sun bear
Not sure if it works but you could try the following
Image
FROM node:16-alpine

WORKDIR /app

COPY package.json ./
COPY package-lock.json ./
RUN npm ci --production

COPY . .

ENV NODE_ENV production

RUN npm run build

EXPOSE 3000

CMD ["npm", "start"]
Image
Image
Avatar
Sun bear
Try following these instructions and hopefully it will work.