惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

月光博客
月光博客
D
Docker
腾讯CDC
J
Java Code Geeks
大猫的无限游戏
大猫的无限游戏
The Cloudflare Blog
Martin Fowler
Martin Fowler
MongoDB | Blog
MongoDB | Blog
博客园 - Franky
博客园 - 三生石上(FineUI控件)
Recent Announcements
Recent Announcements
F
Fortinet All Blogs
IT之家
IT之家
WordPress大学
WordPress大学
M
MIT News - Artificial intelligence
爱范儿
爱范儿
Microsoft Azure Blog
Microsoft Azure Blog
Vercel News
Vercel News
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
小众软件
小众软件
N
Netflix TechBlog - Medium
T
Tailwind CSS Blog
Engineering at Meta
Engineering at Meta
博客园 - 【当耐特】

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Package Next.js App as Nix Derivation and deploy as Servi...
Selim · 2026-05-22 · via DEV Community

Selim

With this method you can package any type of Next.js App including Apps w/ SSR, API Routes, Server Actions and Proxy (Middleware).

Prerequisites

  • Obviously Git
  • Your Next.js App remote Repository w/ package.json and package-lock.json
  • Your NixOS Server

Getting started

  • Add the required output mode to your next.config.ts:
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
    output: "standalone",
};

export default nextConfig;

Enter fullscreen mode Exit fullscreen mode

  • Your npmDepsHash is the unique id of your package-lock.json. We will need it for the next step, so prefetch it:
nix run --extra-experimental-features "nix-command flakes" nixpkgs#prefetch-npm-deps package-lock.json

Enter fullscreen mode Exit fullscreen mode

  • Create your own flake.nix in the same directory as the package.json, make sure to edit the generic "Your Next.js App" Labels and insert your prefetched npmDepsHash from the last step:
{
  description = "Your Next.js App Description";

  # Feel free to choose the input channel yourself 
  inputs = {
    nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
  };

  outputs = { self, nixpkgs }:
    let
      # Support all Nix-capable Systems
      supportedSystems = [
        "x86_64-linux"   # Standard Intel/AMD Linux
        "aarch64-linux"  # ARM Linux
        "x86_64-darwin"  # Intel Macs
        "aarch64-darwin" # Apple Silicon Macs
      ];

      forAllSystems = nixpkgs.lib.genAttrs supportedSystems;
    in {
      packages = forAllSystems (system:
        let
          pkgs = nixpkgs.legacyPackages.${system};
        in {
          default = pkgs.buildNpmPackage {
            pname = "your-nextjs-app";
            version = "1.0.0";
            src = ./.;

            # Insert your prefetched npmDepsHash from the last step
            npmDepsHash = "sha256-...";

            postBuild = ''
              cp -r public .next/standalone/
              cp -r .next/static .next/standalone/.next/
            '';

            installPhase = ''
              cp -r .next/standalone $out
            '';
          };
        }
      );

      nixosModules.default = { config, lib, pkgs, ... }:
        let
          cfg = config.services.your-nextjs-app;

          basePackage = self.packages.${pkgs.system}.default;

          customPackage = basePackage.overrideAttrs (oldAttrs: cfg.environment);
        in {
          options.services.your-nextjs-app = {
            enable = lib.mkEnableOption "Your Next.js App";

            environment = lib.mkOption {
              type = lib.types.attrsOf lib.types.str;
              default = {};
              description = "Key-Value Pairs for Build-Time and Run-Time";
              example = {
                PORT = "3000";
                NODE_ENV = "production";
              };
            };
          };

          config = lib.mkIf cfg.enable {
            systemd.services.your-nextjs-app = {
              description = "Your Next.js App Service";
              wantedBy = [ "multi-user.target" ];
              after = [ "network.target" ];

              environment = cfg.environment;

              serviceConfig = {
                ExecStart = "${pkgs.nodejs_24}/bin/node ${customPackage}/server.js";
                Restart = "always";
              };
            };
          };
        };
    };
}

Enter fullscreen mode Exit fullscreen mode

With every package update and newly added package to your Next.js App you will need to prefetch your npmDepsHash again (repeat step 2) and update your flake.nix.

  • Generate your flake.lock for reproducitbility, commit and push:
nix flake lock --extra-experimental-features "nix-command flakes" && git commit -m "Added flake.nix and flake.lock" && git push

Enter fullscreen mode Exit fullscreen mode

  • Update your NixOS Server. Example minimal NixOS Build Flake, keep in mind to replace all generic values:
{
  description = "Your NixOS Server";

  # Feel free to choose the input channel yourself
  inputs = {
    nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
    your-nextjs-app.url = "github:YourUsername/YourRepository"; 
    # Example input with Codeberg SSH: 
    # "git+ssh://git@codeberg.org/YourUsername/YourRepository.git"
  };

  outputs = { self, nixpkgs, your-nextjs-app, ... }:
    {
      nixosConfigurations = {
        "your-hostname-x86_64" = nixpkgs.lib.nixosSystem {
          system = "x86_64-linux";
          modules = [ configuration.nix ];
        };

        "your-hostname-aarch64" = nixpkgs.lib.nixosSystem {
          system = "aarch64-linux";
          modules = [ configuration.nix ];
        };
      };
    };
}

Enter fullscreen mode Exit fullscreen mode

  • Use the provided Service of your Package. Example minimal configuration.nix in the same directory as flake.nix from step 5, keep in mind to replace all generic values:
{ config, pkgs, lib, ... }:
{
  # Demo User feel free to insert your own
  users.users."your-user" = {
      isNormalUser = true;
      initialPassword = "changeme";
      extraGroups = [ "wheel" ];
      openssh.authorizedKeys.keys = "Your .pub SSH Key";
    };

  services.your-nextjs-app = {
    enable = true;

    # Define all environment variables your App needs
    environment = {
      PORT = "3000";
      NODE_ENV = "production";
    };
  };

  networking = {
    hostname = "your-hostname";

    firewall = {
      enable = true;

      # Open the Port used by your Next.js App
      allowedTCPPorts = [ 3000 ];
    };
}

Enter fullscreen mode Exit fullscreen mode

  • Rebuild your NixOS System, keep in mind to replace all generic values:
nixos-rebuild switch --flake /path/to/flakeAndConf#<your-hostname-x86_64> or <your-hostname-aarch64> --extra-experimental-features "nix-command flakes"

Enter fullscreen mode Exit fullscreen mode

  • Now the your Next.js App should be available as a Service on your NixOS Server. Enjoy <3