Last active
September 6, 2024 15:26
-
-
Save ozgrozer/d6ca4ab3a13d499c5ee28433b50efd54 to your computer and use it in GitHub Desktop.
Next.js: Deploy your app from local to server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { spawn } = require('child_process') | |
// eg: /Users/your-user-name/.ssh/id_rsa | |
const SSH_KEY_PATH = '' | |
// server user name eg: root | |
const SSH_USER = '' | |
// server ip address | |
const SSH_HOST = '' | |
// app path on server eg: /var/www/site.com | |
const SERVER_PATH = '' | |
// use `pm2 list` command to learn | |
const PM2_APP_NAME = '' | |
const runCommand = (command, args, cwd) => { | |
return new Promise((resolve, reject) => { | |
const process = spawn(command, args, { cwd, stdio: 'inherit' }) | |
process.on('close', code => { | |
if (code !== 0) { | |
reject(new Error(`Command failed with exit code ${code}`)) | |
} else { | |
resolve() | |
} | |
}) | |
}) | |
} | |
;(async () => { | |
try { | |
console.log('Building Next.js project...') | |
await runCommand('npm', ['run', 'build'], '.') | |
console.log('Creating tarball of .next directory...') | |
await runCommand( | |
'sh', | |
['-c', 'tar -cf - .next | xz -T0 -9 -c > .next-build.tar.xz'], | |
'.' | |
) | |
console.log('Uploading tarball to server...') | |
await runCommand('rsync', [ | |
'-avz', | |
'-e', | |
`ssh -i ${SSH_KEY_PATH}`, | |
'.next-build.tar.xz', | |
`${SSH_USER}@${SSH_HOST}:${SERVER_PATH}` | |
]) | |
console.log('Performing server-side operations...') | |
await runCommand('ssh', [ | |
'-i', | |
SSH_KEY_PATH, | |
`${SSH_USER}@${SSH_HOST}`, | |
` | |
cd ${SERVER_PATH} && | |
mkdir -p .next.new && | |
tar -xJf .next-build.tar.xz -C .next.new --strip-components=1 && | |
rm -rf .next.old && | |
mv .next .next.old && | |
mv .next.new .next && | |
rm .next-build.tar.xz && | |
pm2 restart ${PM2_APP_NAME} | |
` | |
]) | |
console.log('Removing local tarball...') | |
await runCommand('rm', ['.next-build.tar.xz'], '.') | |
console.log('Deployment completed successfully!') | |
} catch (error) { | |
console.log('Deployment failed:', error) | |
process.exit(1) | |
} | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment