doploy后.env的Next.js问题(Notlify/Vercel)

rm5edbpk  于 2023-03-29  发布在  其他
关注(0)|答案(1)|浏览(135)

我有问题,我的应用程序在next.js afert deploy.在桌面上,启动服务器npm run dev后,一切工作与API完美.布部署后(我尝试Netlify和Vercel)我得到错误,API不接收我的密钥从. env.我尝试与你的_PUBLIC_KEY和NEXT_PUBLIC_YOUR_PUBLIC_KEY,但它是相同的错误.
My .env.local:

YOUR_SERVICE_ID="abc"
YOUR_TEMPLATE_ID="def"
YOUR_PUBLIC_KEY="ghy"

NEXT_PUBLIC_YOUR_SERVICE_ID="abc"
NEXT_PUBLIC_YOUR_TEMPLATE_ID="def"
NEXT_PUBLIC_YOUR_PUBLIC_KEY="ghy"

我的组件:

import Image from "next/image";
import Link from "next/link";
import React, { useRef } from "react";
import { AiOutlineMail } from "react-icons/ai";
import { FaGithub, FaLinkedinIn } from "react-icons/fa";
import { HiOutlineChevronDoubleUp } from "react-icons/hi";
import ContactImg from "../public/assets/contact.jpg";
import emailjs from "@emailjs/browser";

const Contact = () => {
  const form = useRef();

  const sendEmail = (e) => {
    e.preventDefault();

    emailjs
      .sendForm(
        process.env.NEXT_PUBLIC_YOUR_SERVICE_ID,
        process.env.NEXT_PUBLIC_YOUR_TEMPLATE_ID,
        form.current,
        process.env.NEXT_PUBLIC_YOUR_PUBLIC_KEY
      )
      .then(
        (result) => {
          console.log(result.text);
        },
        (error) => {
          console.log(error.text);
        }
      );
    e.target.reset();
  };

  return (
...
)
}

export default Contact;

我的包裹

{
  "name": "portfolio-nextjs",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@emailjs/browser": "^3.10.0",
    "aos": "^3.0.0-beta.6",
    "dotenv": "^16.0.3",
    "gh-pages": "4.0.0",
    "next": "13.2.4",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "react-google-recaptcha": "^2.1.0",
    "react-icons": "4.3.1"
  },
  "devDependencies": {
    "autoprefixer": "10.4.7",
    "eslint": "8.15.0",
    "eslint-config-next": "12.1.6",
    "postcss": "8.4.13",
    "tailwindcss": "3.0.24"
  }
}

和index.js:

import Head from "next/head";
import Contact from "../components/Contact";
import Main from "../components/Main";

export default function Home() {
  return (
    <div>
      <Head>
        <title>Test form app</title>
        <meta
          name="description"
          content="test app with api to send email."
        />
        <link rel="icon" href="/fav.png" />
      </Head>
      <Main />
      <Contact />
    </div>
  );
}

我正在尝试更改.env路径、.env名称、

68bkxrlz

68bkxrlz1#

我解决这个问题:我必须像下面这样更改next.config.js:

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
};

const webpack = require("webpack");

const { parsed: myEnv } = require("dotenv").config({
  path: "/",
});

module.exports = {
  webpack(config) {
    config.plugins.push(new webpack.EnvironmentPlugin(myEnv));
    return config;
  },
};

module.exports = nextConfig;

相关问题