How to Connect Next.js with ASP.NET: A Step-by-Step Guide

As web development evolves, the demand for integrating modern JavaScript frameworks like Next.js with powerful backend frameworks such as ASP.NET is increasing. While both technologies serve different purposes, together they can provide an exceptional development experience. If you're looking to combine Next.js with ASP.NET in a streamlined way, here’s a step-by-step guide based on my recent project setup.

Step 1: Create a Project Using React with ASP.NET Template

To begin, create a project using the reactwithasp template. This is a standard React template with ASP.NET backend integration. The goal here is to replace the React front end with Next.js, but having this initial structure helps to establish the basic client-server relationship.

dotnet new reactwithasp        

This command sets up the necessary ASP.NET backend with a React client project.

Step 2: Delete the Client Project

Since we’re replacing React with Next.js, the next step is to delete the React client project. This will leave you with just the ASP.NET backend.

Navigate to the project folder and delete the ClientApp or Client directory (or whatever name was given to the client folder).

Step 3: Create a New Next.js Project

Next, create a new Next.js project, ensuring it has the same name as the deleted client project to keep the configuration consistent.

npx create-next-app@latest        

For example, if the original client project was named nextjswithasp.client, make sure your new Next.js project has the same name to avoid issues with naming conventions.

Step 4: Set Up an .esproj File

Create a new .esproj file for the client, as this is required to correctly integrate JavaScript/TypeScript projects in the Visual Studio environment.

Here’s an example of the .esproj file you can use, which will be named nextjswithasp.client.esproj:

<Project Sdk="Microsoft.VisualStudio.JavaScript.Sdk/1.0.1184077">

  <PropertyGroup>

    <StartupCommand>npm run dev</StartupCommand>

    <JavaScriptTestRoot>src\</JavaScriptTestRoot>

    <JavaScriptTestFramework>Jest</JavaScriptTestFramework>

    <!-- Allows the build (or compile) script located on package.json to run on Build -->

    <ShouldRunBuildScript>false</ShouldRunBuildScript>

    <!-- Folder where production build objects will be placed -->

    <BuildOutputFolder>$(MSBuildProjectDirectory)\dist</BuildOutputFolder>

  </PropertyGroup>

  <ItemGroup>

    <None Include=".vscode\launch.json" />

  </ItemGroup>

</Project>

        


In this file:

- The StartupCommand is set to run the Next.js development server using npm run dev.

- The output folder for the production build is configured as dist.

Remember, client project names should be in lowercase due to new naming conventions. For example, the client project name in this case would be nextjswithasp.client, and the server-side project name would remain NextjsWithAsp.Server.

Step 5: Configure next.config.js

To complete the Next.js and ASP.NET integration, you’ll need to make a few adjustments to your next.config.js file. This ensures that Next.js communicates properly with the ASP.NET backend.

Here’s the configuration:

/** @type {import('next').NextConfig} */

const nextConfig = {

    reactStrictMode: true,

    webpack: (config) => {

        config.resolve.alias["@"] = "./src";

        return config;

    },

    rewrites: async () => {

        const target = process.env.ASPNETCORE_HTTPS_PORT

            ? https://localhost:${process.env.ASPNETCORE_HTTPS_PORT}

            : process.env.ASPNETCORE_URLS?.split(";")[0] || "https://localhost:7123";

        return [

            {

                source: "/weatherforecast",

                destination: ${target}/weatherforecast,

            },

        ];

    },

};

export default nextConfig;        

This file does the following:

- Aliases the @ symbol to the src directory for easier imports.

- Sets up rewrites for API calls, ensuring that requests made to /weatherforecast are redirected to the ASP.NET backend.

Step 6: Modify the package.json Scripts

Next, install two packages, concurrently and wait-on, to ensure that both the Next.js app and the ASP.NET backend run smoothly together.

Install these dependencies:

npm install concurrently wait-on        

Now, modify the package.json file's dev script to look like this:

"dev": "concurrently \"next dev\" \"wait-on http://localhost:3000 && start http://localhost:3000\"",        

This script allows both the frontend and backend servers to run concurrently. The wait-on command ensures that Next.js starts only after the ASP.NET backend is running.

Step 7: Create a Custom Template (Optional)        

If you plan to use this setup repeatedly, you can create a custom project template using the repository I’ve created.

You can clone the repository here

To create a new template, follow these steps:

1. Navigate to the cloned project folder.

2. Run the following command:

   dotnet new install .        

This will install the project as a new template, which you can then use to create similar projects in the future.

Final Thoughts

By following these steps, you can easily integrate Next.js with an ASP.NET backend, allowing for seamless front-end and back-end development in a single project. This setup is especially useful if you're working in Visual Studio or using .NET for your backend services. Feel free to check out the GitHub repository for a working example and more inspiration!

Happy coding!

To view or add a comment, sign in

More articles by Ankit Poudyal

Insights from the community

Others also viewed

Explore topics