Leveraging the power of Next.js and a tailored deployment strategy using Express and Node

Recently, I encountered an issue while trying to deploy my app that utilizes Next.js on the frontend (including some getStaticProps function) and a custom express/node.js backend on Azure. The backend is connected to MySQL, although I don't believe this is related to the problem at hand. Upon deployment on Azure, I received an error message stating, "You do not have permission to view this directory or page." displayed on the webpage. My express file with all the routes and requests is located in a folder named 'server', and the file itself is called index.js. Additionally, there is a web.config file containing the following configuration:

    <configuration>
      <system.webServer>
        <handlers>
          <add name="iisnode" path="server/index.js" verb="*" modules="iisnode" />
        </handlers>
        <rewrite>
          <rules>
            <rule name="NodeServer" patternSyntax="ECMAScript" stopProcessing="true">
              <match url="server/index.js" />
              <action type="Rewrite" url="server/index.js" />
            </rule>
            <rule name="NextJsRouting" patternSyntax="ECMAScript" stopProcessing="true">
              <match url="^(.*)$" ignoreCase="false" />
              <conditions logicalGrouping="MatchAll">
                <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
              </conditions>
              <action type="Rewrite" url="server/index.js" />
            </rule>
          </rules>
        </rewrite>
        <iisnode nodeProcessCommandLine="&quot;C:\Program Files\nodejs\node.exe&quot;" />
      </system.webServer>
    </configuration>

In addition, there is an iisnode.yml file with the following content:

nodeProcessCommandLine: "node server/index.js"

The contents of the package.json file are as follows:

    {
      "name": "endelig",
      "version": "0.1.0",
      "private": true,
      "scripts": {
        "dev": "nodemon server/index.js",
        "build": "next build",
        "start": "next start",
        "lint": "next lint"
      },
      "dependencies": {
        "@next/font": "13.1.6",
        "@stripe/react-stripe-js": "^2.1.0",
        "@stripe/stripe-js": "^1.52.0",
        "bcrypt": "^5.1.0",
        "cookie-parser": "^1.4.6",
        "dotenv": "^16.0.3",
        "express": "^4.18.2",
        "jsonwebtoken": "^9.0.0",
        "micro": "latest",
        "micro-cors": "latest",
        "mysql": "^2.18.1",
        "next": "^13.1.6",
        "nodemailer": "^6.9.1",
        "react": "18.2.0",
        "react-dom": "18.2.0",
        "stripe": "^11.17.0"
      }
    }

The jsconfig.js file contains the following:

    {
      "compilerOptions": {
        "baseUrl": ".",
        "paths": {
          "@/*": ["./*"]
        }
      }
    }

I have also set up all the necessary environment variables on the Azure web app. However, despite these efforts, I've been struggling with this issue for a few days now. Any assistance or guidance would be greatly appreciated.

After attempting to deploy it on Azure, encountering the error message "(You do not have permission to view this directory or page)" has left me perplexed.

Answer №1

Successfully deployed a Next.js web app in Azure Web App using nodejs and Azure DevOps pipeline:

Ensure that when building the Artifact, it is correctly zipped with the appropriate directory structure as in your local code. Make sure no files are missing when pushing the artifact for deployment:-

trigger:
- main
variables:
  azureSubscription: 'xxxxxxxx94e94d93'
  webAppName: 'siliconwebapp655'
  environmentName: 'siliconwebapp655'
  vmImageName: 'ubuntu-latest'
stages:
- stage: Build
  displayName: Build stage
  jobs:
  - job: Build
    displayName: Build
    pool:
      vmImage: $(vmImageName)
    steps:
    - task: NodeTool@0
      inputs:
        versionSpec: '18.x'
      displayName: 'Install Node.js'
    - script: |
        npm install
        npm run build --if-present
        npm run test --if-present
      displayName: 'npm install, build and test'
    - task: ArchiveFiles@2
      displayName: 'Archive files'
      inputs:
        rootFolderOrFile: '$(System.DefaultWorkingDirectory)'
        includeRootFolder: false
        archiveType: zip
        archiveFile: $(Build.ArtifactStagingDirectory)/$(Build.BuildId).zip
        replaceExistingArchive: true
    - upload: $(Build.ArtifactStagingDirectory)/$(Build.BuildId).zip
      artifact: drop
- stage: Deploy
  displayName: Deploy stage
  dependsOn: Build
  condition: succeeded()
  jobs:
  - deployment: Deploy
    displayName: Deploy
    environment: $(environmentName)
    pool:
      vmImage: $(vmImageName)
    strategy:
      runOnce:
        deploy:
          steps:
          - task: AzureWebApp@1
            displayName: 'Azure Web App Deploy: siliconwebapp655'
            inputs:
              azureSubscription: $(azureSubscription)
              appType: webAppLinux
              appName: $(webAppName)
              runtimeStack: 'NODE|18.10'
              package: $(Pipeline.Workspace)/drop/$(Build.BuildId).zip
              startUpCommand: 'next start'

In the above pipeline, I am building the app and archiving it from System.DefaultWorkingDirectory to

$(Build.ArtifactStagingDirectory)/$(Build.BuildId).zip 
then uploading the build artifact to the drop folder and referencing the same location
$(Pipeline.Workspace)/drop/$(Build.BuildId).zip
in my AzureWebApp@1 deployment task

You do not have permission to view this directory or page

To fix this error, check out my answer on SO thread here

According to the answer:-

Check if all files are deployed correctly by visiting Development Tools > Advanced Tools > Kudu > Go > Site wwwroot >

Verify if all your files are deployed correctly above. If not, rerun the deployment in a new Azure Web app.

Check the Logs by clicking on deployments in Kudu tool and inspect:-

URL:-

https://azure-webapp-name.scm.azurewebsites.net/api/deployments

My app settings:-

Also, refer to the answers from this SO thread

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering a NextJS pre-render issue while generating the sitemap.xml

While developing my markdown-based blog, everything functioned smoothly in the developer environment. However, when I attempted to build the project using the command npm run build, I encountered an error related to pre-rendering failure. Error occurred pr ...

Access a file from an npm module using an executable command

I have a npm module called @jcubic/lips, which includes an executable file. I need to open a file located within the module's directory. This module is installed globally. The specific file I want to access is ../examples/helpers.lips, relative to th ...

What steps can I take to troubleshoot npm install when it is unable to detect my python installation?

npm install is failing and I am determined to make it work. I currently have Python 2 installed, but its location is /usr/bin/python2 instead of /usr/local/bin/python2. Upon running npm install, I encounter the following error message: gyp verb cli &a ...

Testing REST APIs within a Node.js environment by utilizing unit tests that return promises

I have a function within a class that calls a REST API and returns a Promise object. I am able to test the Promise object, but I am unsure how to stub or mock the REST API call for testing. Token.js class Token { getToken(payload) { let authToken ...

Having trouble retrieving data from the database when passing input to a mongoose query using an href tag in Node.js

Welcome to My Schema const AutomationSchema=new mongoose.Schema( {EventName:String, EventDate:String, EventLocation:String, EventDetails:String } ) The Events Model const EventsModel=new mongoose.model("Events",AutomationSchema ...

I'm encountering an issue with enabling Node.js support on PhpStorm as it keeps freezing at the dialog box. Does anyone have a solution for this problem?

Seeking assistance with configuring code support for Vue files in PhpStorm v10.0. Despite having Node and Vue plugins installed, my laptop also has Node(v10.16.3) downloaded. Encountering an issue where PhpStorm freezes at a dialog box, as shown in the sc ...

Is it possible to exclude a portion of the code from running on Heroku staging environment?

Currently, I am looking into testing the functionality of my application by deploying it to the staging environment on Heroku. One specific feature involves saving data to s3, which I only want the application to run when in production mode and skip over ...

Is Firebase the Answer to Shopify's Authentication Validation?

I've been following this tutorial on building a Shopify app using Node, Nextjs, and React. Progress has been smooth so far, but I've now reached a point where I need to store some of my app data in Firestore. My current approach involves utiliz ...

Why am I receiving the error message "Headers cannot be set after being sent to the client"?

I am facing some confusion with this error message and I need help debugging the issue. After researching similar questions, I believe I have identified the part in the code that requires fixing, but I am uncertain about how to proceed. Below is the snipp ...

NextAuth - Instead of redirecting to the callback URL, it remains on the sign-in page

In my current projects involving Next.js and NextAuth, I have a custom sign-in page with the following configurations: Package.json "next": "^12.0.8" "next-auth": "^4.2.1" [..nextauth].js pages:{ signIn:'/au ...

Tips on simulating the Q functions during unit testing in node.js using mocha and rewire!

Struggling with an issue while writing unit tests for node.js. The original code in my file is: var Q=require('q') . . . return Q.all(promises).then(function(data) { _.each(data, function(data) { checking.pu ...

Using the `require` function in Node to access packages installed globally

Currently, I am working with a build system based on gulp. One of my tasks involves accessing npm programmatically (require('npm')). To make this work, I have to include npm in the dependencies section of my package.json, so that it can be found ...

Issue encountered while initializing local environment for SUPABASE: ERROR - The schema "vault" does not exist in the database (SQLSTATE 3F000)

Trying to transition from a hosted db to setting up local and staging environments has proven to be more challenging than anticipated.... Following this helpful guide , I encountered an error after running supabase start. Can anyone offer assistance? I ...

Handle the URL in a manner similar to Express for extracting request parameters in a get operation

Is there a way to extract the parameters from a uri string in a manner identical to Express? Using regex or other methods may not yield consistent results, as it may differ from how Express interprets them. Ideally, I am looking for a solution that mirrors ...

I am experiencing difficulties with socket.io and my Flutter app is unable to establish a connection with the server or backend component

For the backend of my flutter app, I utilized socket.io and node.js. I created an index.json file and implemented a function on a page to establish a connection between my app and the backend. However, I am facing issues with it not working as expected. Be ...

Data should only be sent to Coveralls from Travis, and should not be sent when running tests locally

I currently have an application (https://github.com/idmillington/dendry) that utilizes Travis CI to monitor build status. I make use of Istanbul to produce a coverage report, and my goal is to send this data to Coveralls in order to generate a coverage but ...

Using Docker with Next.js allows me to access the website exclusively through port 3000

When using Next.js with Docker, I access the website by going to "site.com:3000". But ideally, I would like to simply go to my site by visiting "site.com". I'm puzzled as to why 3000 is being appended at the end. It appears tha ...

Encountering an error while running `npm start` in Angular

Attempting to utilize AngularJS with live preview using the following command: npm start Current npm version: 4.3.0 Encountering the following errors: Microsoft Windows [Version 10.0.14393] (c) 2016 Microsoft Corporation. All rights reserved. C:&b ...

What is the best way to transform a date such as '2021-06-01T11:17:00-07:00' into the corresponding date and time for a specific location (New Delhi) using JavaScript?

How can I convert a date in the format '2021-06-01T11:17:00-07:00' to ISO standard? What does this format represent? let date = new Date('2021-06-01T11:17:00-07:00'); console.log(date.getHours() + " :" + date.getMinutes()); I ...

How to fix the "Module not found" error on local NodeJS modules?

I understand that the most optimal way to install npm packages is using npm install. However, I am unable to do so on the professional server I am working on. Instead, I have to manually clone the node modules repository using git clone <node_module_git ...