DEV Community

panfan
panfan

Posted on

Next.js - Environment Variables

Next.js 内置了对环境变量的支持,让你可以执行以下操作:

  • 使用 .env.local 加载环境变量
  • 通过给环境变量添加 NEXT_PUBLIC_ `前缀将环境变量暴露给浏览器

创建环境变量

bash
DB_HOST=localhost
DB_USR=root
DB_PWD=123456

创建 env.js

`jsx
import Head from 'next/head'
import Container from '../../components/container'

export default function FirstPost(props) {
return (
<>


Environment Variables

Database Credentials


Host: {props.host}


Username: {props.username}


Password: {props.password}



</>
)
}

export async function getStaticProps() {
// Connect to Database using DB properties
return {
props: {
host: process.env.DB_HOST,
username: process.env.DB_USER,
password: process.env.DB_PASS
}
}
}
`

Next.js会在.env*中自动扩展变量,即可以定义变量

bash
HOSTNAME=localhost
PORT=3000
HOST=http://$HOSTNAME:$PORT

Top comments (0)