Azure / static-web-apps

Azure Static Web Apps. For bugs and feature requests, please create an issue in this repo. For community discussions, latest updates, kindly refer to the Discussions Tab. To know what's new in Static Web Apps, visit https://aka.ms/swa/ThisMonth
https://aka.ms/swa
MIT License
332 stars 57 forks source link

Next auth with nextjs not working azure static webapp #1524

Closed mukeysh-k closed 3 months ago

mukeysh-k commented 4 months ago

Describe the bug

NextAuth.js functionality is not working in Azure Static Web Apps, while other APIs seem to be functioning correctly. When attempting to log in, the request to /api/auth/providers returns a 500 Bad Request error with the message "message":"There is a problem with the server configuration. Check the server logs for more information.". and redirected to me "api/auth/error"

I am using GitHub for deployment and setting up the environment variable there.

This is working fine locally.

github actions:
name: Azure Static Web Apps CI/CD

on:
  push:
    branches:
      - main
  pull_request:
    types: [opened, synchronize, reopened, closed]
    branches:
      - main

jobs:
  build_and_deploy_job:
    if: github.event_name == 'push' || (github.event_name == 'pull_request' && github.event.action != 'closed')
    runs-on: ubuntu-latest
    name: Build and Deploy Job
    steps:
      - uses: actions/checkout@v3
        with:
          submodules: true
          lfs: false
      - name: Build And Deploy
        id: builddeploy
        uses: Azure/static-web-apps-deploy@v1
        with:
          azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN }}
          repo_token: ${{ secrets.GITHUB_TOKEN }} # Used for Github integrations (i.e. PR comments)
          action: "upload"
          ###### Repository/Build Configurations - These values can be configured to match your app requirements. ######
          # For more information regarding Static Web App workflow configurations, please visit: https://aka.ms/swaworkflowconfig
          app_location: "/" # App source code path
          api_location: "" # Api source code path - optional
          output_location: "" # Built app content directory - optional
        env:
          NEXTAUTH_URL: ${{ vars.NEXTAUTH_URL }}
          NEXT_PUBLIC_BASEURL: ${{ vars.PUBLIC_BASEURL }}
          NEXTAUTH_SECRET: ${{ secrets.NEXT_AUTH_SECRET}}
          ###### End of Repository/Build Configurations ######

  close_pull_request_job:
    if: github.event_name == 'pull_request' && github.event.action == 'closed'
    runs-on: ubuntu-latest
    name: Close Pull Request Job
    steps:
      - name: Close Pull Request
        id: closepullrequest
        uses: Azure/static-web-apps-deploy@v1
        with:
          azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN }}
          action: "close"

Next Auth code

import NextAuth from "next-auth";
import { authOptions } from "@/app/lib/auth";

const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };

import { NextAuthOptions } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import jwt, { JwtPayload } from "jsonwebtoken";
export const authOptions: NextAuthOptions = {
  debug: process.env.NODE_ENV === "development",
  providers: [
    CredentialsProvider({
      name: "credentials",
      credentials: {
        email: { label: "Email", type: "email" },
        password: { label: "Password", type: "password" },
      },
      async authorize(credentials) {
        try {
          console.log("NASA", process.env.NEXTAUTH_SECRET);
          console.log("NAU", process.env.NEXTAUTH_URL);
          const res = await fetch(`${process.env.NEXT_PUBLIC_BASEURL}/login`, {
            method: "POST",
            body: JSON.stringify(credentials),
            headers: { "Content-Type": "application/json" },
          });
          const user = await res.json();

          // If no error and we have user data, return it
          if (res.ok && user) {
            return user;
          }
          // Return null if user data could not be retrieved
          return null;
        } catch (error) {
          console.log("Error: ", error);
          return null;
        }
      },
    }),
  ],
  session: {
    strategy: "jwt",
    maxAge: 1 * 60 * 60,
  },
  pages: {
    signIn: "/",
  },

  callbacks: {
    async session({ session, token }: { session: any; token: any }) {
      if (session?.user) {
        session.accessToken = token.accessToken;
      }
      return session;
    },
    async jwt({ user, token }: { user: any; token: any }) {
      if (user) {
        token.accessToken = user.token;
      }
      return token;
    },
  },
  secret: process.env.NEXTAUTH_SECRET,
};

"next": "14.2.3", "next-auth": "^4.22.1",

What I am doing wrong here? Any help would be appreciated.

mukeysh-k commented 3 months ago

I have fixed this by adding NEXTAUTH_SECRET in the azure static web app environment variables.