# Deploying a NextJS app directly via the build process

Install 2 packages as development dependencies (will be set to **devDependencies** in the same package.json that's used for the NextJS application): I realize we're having the same package.json file for the NextJS application and the nodeJS script - that's not an issue, just make sure that the nodeJS packages we're using for this upload functionality are saved as **dev** only.

```bash
npm i node-scp dotenv --save-dev
```

Create a .env file with the following details :

```plaintext
HOST="mydomain.com"
USERNAME="username"
PASSWORD="MyPassword"
PORT="22"
LOCAL_FOLDER="./out"
REMOTE_FOLDER="/home/myUsername/apps/myNextJSApp"
```

I am using [OpalStack](https://opalstack.com) where each application's *root* path is pre-set to ~/apps/appName, so my REMOTE\_FOLDER is /home/myUsername/apps/myNextJSApp - but for most other hosting companies, it'll be something like /home/myUsername/public\_html

Next, create an **upload.mjs** file in the *root* directory as the NextJS app - we need to save the file as a .mjs file though since we can't set `"type": "module"` in package.json file which is being used by NextJS also. Enter into upload.mjs :

```javascript
import * as dotenv from 'dotenv'
import { Client } from 'node-scp';

dotenv.config();

var remote_server =
{
    host: process.env.HOST,
    port: process.env.PORT,
    username: process.env.USERNAME,
    password: process.env.PASSWORD,
    // forceIPv4: boolean,
    // forceIPv6: boolean,
    // privateKey: fs.readFileSync('./key.pem'),
    // passphrase: 'your key passphrase', 
}

const upload = async () =>
{
    try
    {
        const client = await Client(remote_server);
        console.log("Uploading .... ");
        await client.uploadDir(process.env.LOCAL_FOLDER, process.env.REMOTE_FOLDER);
        client.close();
        console.log("Upload Done");
    }
    catch (e)
    {
        console.log(e);
    }
  }
  
upload();
```

Now edit the package.json file to include this :

```json
"build": "next build && next export && node upload.mjs",
```

After you've tested your app via `npm run dev`, you can now run `npm run build` and it'll build and export followed by uploading your **out** folder (which is the default NextJS's build folder) to your server's NextJS path.
