Open olavocarvalho opened 1 year ago
Hi olavocarvalho,
I can only share some experience I made: Did you check for example that all environment variables are set correctly under environments in the static web app settings? We had the same issue with next.js and next-auth, but it was due to some missing configuration of environment variables on our side. In our case the mongodb was not connecting well and it lead to the case that next-auth code crashed.
So it might also be that some code fragments related to your authentication process are crashing and leading to next-auth not working.
Later on next-auth was working for me with pages as well as app routes.
To be honest, debugging this error is not easy with the information provided by azure portal.
Hope this helps. Shouts to the SWA Team providing Next.js support <3
---- UPDATE
Now experiencing similar issue. Strangely Next-Auth api calls are working but back end api generated by server component is not accessable.
Call Stack: System.InvalidOperationException: at Mono.Unix.UnixFileSystemInfo.AssertValid (Mono.Posix.NETStandard, Version=1.0.0.0, Culture=neutral, PublicKeyToken=***) at Microsoft.Azure.WebJobs.Script.Workers.Http.HttpWorkerProcess.AssignUserExecutePermissionsIfNotExists (Microsoft.Azure.WebJobs.Script, Version=4.21.0.0, Culture=neutral, PublicKeyToken=null: /src/azure-functions-host/src/WebJobs.Script/Workers/Http/HttpWorkerProcess.cs:75)
Having a similar issue, brand new Next.JS install on 13.1 with next-auth. Working fine locally, throwing errors on azure static apps
I experience exactly the same issue as well Next 13.4.5 very simple API endpoint and I see these errors in the logs once hosted on Azure static webb app.
I'm also seeing this on next@13.2.3.
It looks like there's a problem with converting API routes because the mapped function route (next_function.js) is being treated as an ES module instead of CommonJS. Here's my logs:
Initializing Warmup Extension.
Initializing Host. OperationId: '{...}'.
Host initialization: ConsecutiveErrors=0, StartupCount=2, OperationId={...}
"ApplicationInsightsLoggerOptions {...}"
"LoggerFilterOptions {...}"
"LoggerFilterOptions {...}"
"ConcurrencyOptions {...}"
"FunctionResultAggregatorOptions {...}"
"SingletonOptions {...}"
"ScaleOptions {...}"
Starting JobHost
Starting Host (HostId={...}, InstanceId={...}, Version=4.21.3.3, ProcessId=17654, AppDomainId=1, InDebugMode=False, InDiagnosticMode=False, FunctionsExtensionVersion=~4)
FUNCTIONS_WORKER_RUNTIME set to node. Skipping WorkerConfig for language: java
FUNCTIONS_WORKER_RUNTIME set to node. Skipping WorkerConfig for language: powershell
FUNCTIONS_WORKER_RUNTIME set to node. Skipping WorkerConfig for language: python
Loading functions metadata
Reading functions metadata
1 functions found
1 functions loaded
Error while assigning execute permission.
Generating 1 job function(s)
"Found the following functions: Host.Functions.next_function"
"HttpOptions {...}"
"Initializing function HTTP routes Mapped function route 'api/{*fullpath}' [all] to 'next_function'"
Host initialized (211ms)
Host started (237ms)
Job host started
file:///home/site/wwwroot/next_function.js:2
const NextServer = require('next/dist/server/next-server').default
^
n/a
ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and '/home/site/wwwroot/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
at file:///home/site/wwwroot/next_function.js:2:20
at ModuleJob.run (node:internal/modules/esm/module_job:194:25)
n/a
Node.js v18.16.0
Language Worker Process exited. Pid=17692.
Error while assigning execute permission.
file:///home/site/wwwroot/next_function.js:2
const NextServer = require('next/dist/server/next-server').default
^
n/a
ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and '/home/site/wwwroot/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
at file:///home/site/wwwroot/next_function.js:2:20
at ModuleJob.run (node:internal/modules/esm/module_job:194:25)
n/a
Node.js v18.16.0
Language Worker Process exited. Pid=17703.
Error while assigning execute permission.
file:///home/site/wwwroot/next_function.js:2
const NextServer = require('next/dist/server/next-server').default
^
n/a
ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and '/home/site/wwwroot/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
at file:///home/site/wwwroot/next_function.js:2:20
at ModuleJob.run (node:internal/modules/esm/module_job:194:25)
n/a
Node.js v18.16.0
Language Worker Process exited. Pid=17714.
Exceeded http worker restart retry count. Shutting down Functions Host
Stopping JobHost
Job host stopped
I encountered the same issue and thanks to sebastian's comment above, I checked all environment variables and discovered that the cause of my problem was environment variable substitution, which doesn't seem to work with Azure Static Web Apps.
Previously I had:
NEXTAUTH_URL="${APP_URL}"
DATABASE_URL="sqlserver://${DATABASE_HOST}:${DATABASE_PORT};database=${DATABASE_NAME};user=${DATABASE_USER};password=${DATABASE_PASSWORD};encrypt=true"
After replacing these with plain text strings, everything started working as expected!
This thread was very helpful, and I wanted to document my findings for any who follow.
In particular, if you set variables like this in Azure Pipelines:
name: Azure Static Web Apps CI/CD
pr:
branches:
include:
- main
trigger:
branches:
include:
- main
jobs:
- job: build_and_deploy_job
displayName: Build and Deploy Job
condition: or(eq(variables['Build.Reason'], 'Manual'),or(eq(variables['Build.Reason'], 'PullRequest'),eq(variables['Build.Reason'], 'IndividualCI')))
pool:
vmImage: ubuntu-latest
variables:
- group: Azure-Static-Web-Apps-YOURS-variable-group
steps:
- checkout: self
submodules: true
- task: AzureStaticWebApp@0
inputs:
azure_static_web_apps_api_token: $(AZURE_STATIC_WEB_APPS_API_TOKEN_YOURS)
###### 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
###### End of Repository/Build Configurations ######
env:
MY_ENV_VAR: "Anything"
Then process.env.MY_ENV_VAR
will not be populated, whether you use SSR or not. This is clear as mud in Azure's documentation.
In fact, the correct way to set an environment variable for a SWA is to go into the SWA page in Azure Portal, then to Configuration and Application Settings. Variables you set there will be populated in process.env.
This confusion was an aspect of the problem I'm encountering, but not the entire solution. I suspect that the rest of the puzzle is related to @justinh-kairos's comment above, but I don't have an answer to that yet. I will update when I do.
Update: The error
System.InvalidOperationException:
at Mono.Unix.UnixFileSystemInfo.AssertValid (Mono.Posix.NETStandard, Version=1.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51)
at Microsoft.Azure.WebJobs.Script.Workers.Http.HttpWorkerProcess.AssignUserExecutePermissionsIfNotExists (Microsoft.Azure.WebJobs.Script, Version=4.27.0.0, Culture=neutral, PublicKeyToken=null: /src/azure-functions-host/src/WebJobs.Script/Workers/Http/HttpWorkerProcess.cs:76)
was a red herring. It did not actually affect our deployment, and the problem was a misconfiguration.
Seeing the same using SWA CLI
swa deploy .next/standalone --deployment-token=XXXXX --env=production --api-language "node" --api-version "18"
6/11/2023, 11:27:44.164 am Starting JobHost
6/11/2023, 11:27:44.165 am Starting Host (HostId=155ad108-3d63-4e1e-bc11-abca0516, InstanceId=5bfcd185-248c-483e-b9c8-6c8bcfc9e475, Version=4.27.5.5, ProcessId=3541, AppDomainId=1, InDebugMode=True, InDiagnosticMode=False, FunctionsExtensionVersion=~4)
6/11/2023, 11:27:44.175 am FUNCTIONS_WORKER_RUNTIME set to node. Skipping WorkerConfig for language: python
6/11/2023, 11:27:44.176 am Loading functions metadata
6/11/2023, 11:27:44.211 am Reading functions metadata (Custom)
6/11/2023, 11:27:44.213 am 1 functions found (Custom)
6/11/2023, 11:27:44.213 am 1 functions loaded
6/11/2023, 11:27:44.245 am Error while assigning execute permission.
6/11/2023, 11:27:44.330 am Generating 1 job function(s)
6/11/2023, 11:27:44.373 am "Found the following functions:
Host.Functions.next_function"
6/11/2023, 11:27:44.381 am "HttpOptions
{
""DynamicThrottlesEnabled"": false,
""EnableChunkedRequestBinding"": false,
""MaxConcurrentRequests"": -1,
""MaxOutstandingRequests"": -1,
""RoutePrefix"": ""api""
}"
6/11/2023, 11:27:44.382 am "Initializing function HTTP routes
Mapped function route 'api/{*fullpath}' [all] to 'next_function'"
6/11/2023, 11:27:44.383 am Host initialized (217ms)
6/11/2023, 11:27:44.386 am Host started (220ms)
6/11/2023, 11:27:44.386 am Job host started
6/11/2023, 11:27:45.515 am /home/site/wwwroot/node_modules/next/dist/server/web/spec-extension/request.js:28
6/11/2023, 11:27:45.515 am class NextRequest extends Request {
6/11/2023, 11:27:45.517 am ^
6/11/2023, 11:27:45.517 am n/a
6/11/2023, 11:27:45.538 am Language Worker Process exited. Pid=3585.
6/11/2023, 11:27:45.548 am ReferenceError: Request is not defined
6/11/2023, 11:27:45.549 am at Object.<anonymous> (/home/site/wwwroot/node_modules/next/dist/server/web/spec-extension/request.js:28:27)
6/11/2023, 11:27:45.549 am at Module._compile (node:internal/modules/cjs/loader:1198:14)
6/11/2023, 11:27:45.549 am at Object.Module._extensions..js (node:internal/modules/cjs/loader:1252:10)
6/11/2023, 11:27:45.549 am at Module.load (node:internal/modules/cjs/loader:1076:32)
6/11/2023, 11:27:45.550 am at Function.Module._load (node:internal/modules/cjs/loader:911:12)
6/11/2023, 11:27:45.553 am at Module.require (node:internal/modules/cjs/loader:1100:19)
6/11/2023, 11:27:45.554 am at Module.mod.require (/home/site/wwwroot/node_modules/next/dist/server/require-hook.js:64:28)
6/11/2023, 11:27:45.554 am at require (node:internal/modules/cjs/helpers:119:18)
6/11/2023, 11:27:45.554 am at Object.<anonymous> (/home/site/wwwroot/node_modules/next/dist/server/web/spec-extension/adapters/next-request.js:37:18)
6/11/2023, 11:27:45.554 am at Module._compile (node:internal/modules/cjs/loader:1198:14)
6/11/2023, 11:27:45.569 am Error while assigning execute permission.
Last block repeats until the worker restart retry count is exceeded, then the Functions Host is shutdown.
I have an Next.js App version 13.4.3 with next-auth 4.22.1 as authentication middleware with Azure AD B2C as provider. The first pages that I created was working as expected but as soon as I added a really simple API endpoint to handle a form submission the app started to crash after the deployment to Azure Static Web Apps (I also using the standalone version due to 100mb limitation). After the endpoint addition, the app is not instanced anymore. Here is the logs from the SWA:
To Reproduce Steps to reproduce the behavior:
I can share the repository and azure config and pipeline files in private
Expected behavior The app running and receiving requests in the API