Next.js Tutorial - Part 10 | Environment Variables and Runtime Configuration (ok)

https://www.youtube.com/watch?v=7J4iL1HDshQ&list=PLYSZyzpwBEWSQsrukurP09ksi49H9Yj40

Xem videos tại E:\Desktop\Youtube 2020 Nextjs

1. Use cross-env

C:\Users\Administrator\Desktop\nextjs\package.json

{
  "name": "nextjs",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "cross-env MY_STEP=build next build",
    "start": "cross-env MY_SECRET=1234 MY_STEP=start next start"
  },
  "dependencies": {
    "cross-env": "^7.0.3",
    "dotenv": "^8.2.0",
    "next": "10.0.3",
    "react": "17.0.1",
    "react-dom": "17.0.1"
  }
}

C:\Users\Administrator\Desktop\nextjs\next.config.js

module.exports = {
  env: {
    STEP: process.env.MY_STEP,
  },
  serverRuntimeConfig: {
    // Will only be available on the server side
    MY_SECRET: process.env.MY_SECRET,
  },
  publicRuntimeConfig: {
    // Will be available on both server and client
    API_ENDPOINT: '/myapi/version/1',
  },
};

C:\Users\Administrator\Desktop\nextjs\pages\gssp.js

import getConfig from 'next/config';
// Only holds serverRuntimeConfig and publicRuntimeConfig
const { serverRuntimeConfig, publicRuntimeConfig } = getConfig();
// Will only be available on the server-side
console.log(serverRuntimeConfig.MY_SECRET);
// Will be available on both server-side and client-side
console.log(publicRuntimeConfig.API_ENDPOINT);
export default function Gssp(props) {
  return (
    <div>
      API_ENDPOINT: {publicRuntimeConfig.API_ENDPOINT}
      <pre>
        Props: {JSON.stringify(props, null, 2)}
      </pre>
    </div>
  );
}
export const getServerSideProps = () => {
  return {
    props: {
      MY_SECRET: serverRuntimeConfig.MY_SECRET,
      API_ENDPOINT: publicRuntimeConfig.API_ENDPOINT,
    },
  };
};

2. dotenv custom croos-env

C:\Users\Administrator\Desktop\nextjs\package.json

Bỏ cross-env MY_STEP=build trong "build": "next build khi đó

{
  "name": "nextjs",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build", // cross-env MY_STEP=build 
    // "build": "cross-env MY_STEP=build next build",
    "start": "cross-env MY_SECRET=1234 MY_STEP=start next start"
  },
  "dependencies": {
    "cross-env": "^7.0.3",
    "dotenv": "^8.2.0",
    "next": "10.0.3",
    "react": "17.0.1",
    "react-dom": "17.0.1"
  }
}

C:\Users\Administrator\Desktop\nextjs\next.config.js

require('dotenv').config();
module.exports = {
  env: {
    STEP: process.env.MY_STEP,
  },
  serverRuntimeConfig: {
    // Will only be available on the server side
    MY_SECRET: process.env.MY_SECRET,
  },
  publicRuntimeConfig: {
    // Will be available on both server and client
    API_ENDPOINT: '/myapi/version/1',
  },
};

Last updated

Was this helpful?