Azure / Azure/static-web-apps

Page on Static Web App throw a 500 error when I used getServerSideProps from Next.js

Open
#1,182 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
No language data
Stars
346
Forks
67
PR merge metrics
No merged PRs in 30d

Description

### Discussed in https://github.com/Azure/static-web-apps/discussions/1181

Originally posted by **aadlc** May 26, 2023
I am not sure why the app works as expected on my local, but as soon it is published as a Static Web App on Azure, it throws a 500 Internal Server Error.

It is my first Next.js app on Azure. Perhaps I am missing something, a configuration, settings, etc. ?
Or,
Something wrong on my code?

Any way, your help will be appreciated.

## Summary

I believe the problem is caused by `getServerSideProps` method from Next.js. In my application, `getServerSideProps` calls a public API that returns a token (JWT) that is used in subsequent calls.

### What have a I tried
1. Initially, I thought the environment variables were not pulled into the application by build process.

- I hardcode the `process.env.CPL_API_USER_PROD` and `process.env.CPL_API_PSWRD_PROD` values on the `getCplApiToken` method. I got the 500 error.
- I used `getStaticProps` from next.js, returned `process.env.CPL_API_USER_PROD` from it, then logged the variable value to the browser console. The correct value was logged, this worked on local and Azure.

2. All of the environment variables are saved as gitHub secrets, and their names match the ones on my `.env.local` file.
![image](https://github.com/Azure/static-web-apps/assets/5083778/562d0e2c-70dd-44dd-80fd-bcdaae640248)
![image](https://github.com/Azure/static-web-apps/assets/5083778/ed748e10-8ae4-41e2-9be1-9dd92bd6ab3c)

3. I commented the `getServerSideProps` code in my page.
- The 500 error disappear on Azure.

4. **IMPORTANT** : deployed application to Vercel
- **Worked as expected**. No 500 error message


### My code

```
import { useEffect } from 'react'
import { useRouter } from 'next/router'
import { Box, Button, Typography } from '@mui/material'
import TextFieldCustom from '@/components/TextField'
import FormLayout from '@/components/FormLayout'
import useCustomForm from '@/hooks/useCustomForm'
import { yupResolver } from '@hookform/resolvers/yup'
import {schema} from '@/lib/frm1-schema'
import {defaultValues} from '@/lib/frm1-defaultValues'
import getCplApiToken from '@/api/getCplApiToken'
import usePasswordManagementStore from '@/store/passwordManagementStore'

export async function getServerSideProps() {

const resObj = await getCplApiToken()
return {
props: {
serverProps: {status: resObj.status, token: resObj.data[0].token}
}, // will be passed to the page component as props
}
}
const Form = ({ serverProps }) => {
const { bearerToken, setBearerToken, setAccountData } = usePasswordManagementStore()
const router = useRouter()
const {
control,
formState: { errors },
handleSubmit,
watch
} = useCustomForm({
mode: 'all',
defaultValues: defaultValues,
shouldUnregister: true,
resolver: yupResolver(schema)
})

const formData = watch()

const isEmptyFieldPresent = Object.values(formData).some(
(value) => value === '' || value === null)

useEffect(() => {
if (!bearerToken)
{
setBearerToken(serverProps.token)
}
}, [bearerToken, setBearerToken])

const submit = data => {
setAccountData(data)
router.push('/password-management/account-validation')
}
return (


PIN Reset
Reset your PIN securely

Receive a validation code via email or SMS to the associated contact information on your library account.


Need help? Contact library staff.






Next





)
}

export default Form
```

While the code in the method called inside getServerSideProps is:

```
import fetch from 'node-fetch'
const myHeaders = {'Content-Type': 'application/json'}
const getCplApiToken = async () => {
let ret = null
let response = null
let data = null
const controller = new AbortController()

const raw = JSON.stringify({
username: process.env.CPL_API_USER_PROD,
password: process.env.CPL_API_PSWRD_PROD
})

const requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow',
}

try {
response = await fetch(`${process.env.NEXT_PUBLIC_CPL_API_URL_PROD}/Auth`, requestOptions)
// setTimeout(id)
if (!response.ok) {
const resError = await response.text()
throw resError
}
data = await response.text()
ret = JSON.parse(data)
} catch (error) {
// ret = JSON.parse(error)
console.log(error)
}
return { status: response.status, data: ret }
}

export default getCplApiToken
```
### Yml file

```name: Azure Static Web Apps CI/CD

on:
push:
branches:
- staging
pull_request:
types: [opened, synchronize, reopened, closed]
branches:
- staging
jobs:
build_and_deploy_job:
if: github.event_name == 'push' || (github.event_name == 'pull_request' && github.event.action != 'closed')
runs-on: ubuntu-latest
name: Build and Deploy Job
steps:
- uses: actions/checkout@v3
with:
submodules: true
- name: Build And Deploy
id: builddeploy
uses: Azure/static-web-apps-deploy@v1
env:
CPL_API_USER_PROD: ${{ secrets.CPL_API_USER_PROD }}
CPL_API_PSWRD_PROD: ${{ secrets.CPL_API_PSWRD_PROD }}
CPL_API_URL_PROD: ${{ secrets.CPL_API_URL_PROD }}
NEXT_PUBLIC_CPL_API_URL_PROD: ${{ secrets.CPL_API_URL_PROD }}
with:
azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN_POLITE_FIELD_09B90541E }}
repo_token: ${{ secrets.GITHUB_TOKEN }} # Used for Github integrations (i.e. PR comments)
action: "upload"
###### Repository/Build Configurations - These values can be configured to match your app requirements. ######
# For more information regarding Static Web App workflow configurations, please visit: https://aka.ms/swaworkflowconfig
app_location: "/" # App source code path
api_location: "" # Api source code path - optional
output_location: "" # Built app content directory - optional
app_build_command: npm run build
api_build_command: 'rm -rf ./node_modules/@next/swc-* && rm -rf ./.next/cache'
###### End of Repository/Build Configurations ######


close_pull_request_job:
if: github.event_name == 'pull_request' && github.event.action == 'closed'
runs-on: ubuntu-latest
name: Close Pull Request Job
steps:
- name: Close Pull Request
id: closepullrequest
uses: Azure/static-web-apps-deploy@v1
with:
azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN_POLITE_FIELD_09B90541E }}
action: "close"

```

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.